PostgreSQL:查询记录,其中所有联接的记录属性都与where子句

时间:2018-09-28 17:18:18

标签: ruby-on-rails postgresql

我发现了一个类似的问题,但不满足我的回答:SQL: Select records where ALL joined records satisfy some condition

我有两个表ordersshipments

orders have_many shipments

货件的属性状态为open/closed

我想查询所有发货为closed的订单:

假设表:

  • order1、2批装运:1个打开,1个关闭
  • order2,共3批货:1open,2closed
  • order3,1发货:0open,1closed
  • order4,2批货物:0open,2closed

运行查询将返回order3order4的记录

我目前正在使用应用程序代码对N + 1进行此操作,我想仅在SQL中实现。

2 个答案:

答案 0 :(得分:2)

让我们查找所有状态为closed以外的,没有任何货件(匹配该订单)的订单。

Order.where("NOT EXISTS(SELECT 1 FROM shipments WHERE shipments.order_id = orders.id AND status != 'closed')"

答案 1 :(得分:1)

demo:db<>fiddle

汇总状态,然后可以使用ALL运算符进行过滤,该运算符将检查所有数组元素是否都符合条件。

SELECT order_id
FROM (
    SELECT order_id, array_agg(status) status
    FROM shipments
    GROUP BY order_id
) s
WHERE 'closed' = ALL(status)
相关问题