怎么做Arel中的“where exists”

时间:2011-06-01 20:19:39

标签: sql ruby database ruby-on-rails-3 arel

如何在Arel中执行包含“where exists”的查询?例如,在这样的查询中,向所有供应商显示至少一个订单:

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

我在Arel docs http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists中看到“存在”,但我在使用它时遇到了麻烦。

2 个答案:

答案 0 :(得分:25)

你走了:

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`))"

尽管如此,内部联接会以更简单的方式执行此操作 - 最终效果不佳 -

  

Supplier.joins:orders

答案 1 :(得分:-1)

我认为你可以整齐地使用counter_cache:

http://asciicasts.com/episodes/23-counter-cache-column

相关问题