Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "where exists" in Arel

How do you do a query that includes a "where exists" in Arel? For example on a query like this to show all the suppliers with at least one order:

SELECT *
FROM suppliers
WHERE EXISTS
  (SELECT *
    FROM orders
    WHERE suppliers.supplier_id = orders.supplier_id);

I see "exists" in the Arel docs http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists but I'm having trouble using it.

like image 467
Nathan Hurst Avatar asked Jun 01 '11 20:06

Nathan Hurst


People also ask

What is Arel Ruby?

Arel is a SQL AST manager for Ruby. It. simplifies the generation of complex SQL queries, and. adapts to various RDBMSes.

What is Arel query?

Arel is a SQL abstraction that ActiveRecord uses to build SQL queries. Arel wraps each component of the SQL query language with Ruby objects and provides an expressive DSL for composing SQL queries. When using Arel, you're mainly interacting with tables ( Arel::Table ) and nodes ( Arel::Nodes::Node subclasses).


1 Answers

Here you go:

suppliers= Supplier.arel_table
orders= Order.arel_table
suppliers_with_orders = Supplier.where(
                          Order.where(orders[:supplier_id]
                                        .eq(suppliers[:id])).exists).to_sql =>
"SELECT `suppliers`.* FROM `suppliers` 
 WHERE (EXISTS (SELECT `orders`.* 
                FROM `orders` 
                WHERE `suppliers`.`id` = `orders`.`supplier_id`))"

Though, an inner join would do this in a more simple - and eventually less performant - way :

Supplier.joins :orders

like image 114
Pedro Rolo Avatar answered Oct 13 '22 20:10

Pedro Rolo