如何使用“不在”和带有活动记录的子查询来执行where子句

时间:2018-11-05 23:47:24

标签: sql postgresql activerecord arel

我该如何用activerecord(在轨道上为红宝石)编写这样的子查询:

SELECT id, unit_cdl_required, load_group_id
FROM loads lo
WHERE unit_cdl_required=FALSE AND
load_group_id NOT IN (
  SELECT load_group_id
  FROM loads
  WHERE unit_cdl_required=TRUE
  AND load_group_id=lo.load_group_id
);

我尝试过:

Load.where("unit_cdl_required=FALSE AND load_group_id NOT IN (SELECT load_group_id FROM loads WHERE unit_cdl_required=TRUE AND load_group_id=lo.load_group_id)")

但是得到了ERROR: missing FROM-clause entry for table "lo"

我的模式如下:https://imgur.com/a/wr9Yzl2

1 个答案:

答案 0 :(得分:0)

您有一个奇怪的内置SQL查询,也许您想做这样的事情:

SELECT id, unit_cdl_required, load_group_id FROM loads
LEFT JOIN loads AS required_loads ON required_loads.unit_cdl_required = TRUE
                AND required_loads.load_group_id = loads.load_group_id
WHERE loads.unit_cdl_required = TRUE AND required_loads.id IS NULL

然后我们将得到类似这样的东西:

Load.join(
  "LEFT JOIN loads AS required_loads ON required_loads.unit_cdl_required = TRUE AND required_loads.load_group_id = loads.load_group_id"
).where('loads.unit_cdl_required = FALSE AND required_loads.id IS NULL')

有一个更漂亮的解决方案

Load.where(unit_cdl_required: false)
    .where.not(
      load_group_id: Load.where(unit_cdl_required: true).pluck(:load_group_id)
    )