我有两张桌子,人物和车辆。车辆属于人民。
我有一个报告/查询,显示哪些人没有车辆。我试图将它合并到我的rails应用程序中,以便在有人想要查看此信息时运行它。我决定为它编写一个范围,但无法使范围正常工作。代码如下。有什么想法吗?
scope :person_has_no_vehicle, -> { joins(:vehicles).where('Vehicles.person_id IS NULL')}
查询在
下面SELECT DISTINCT
People.ID,
People.nam_first,
People.nam_last
FROM
People
LEFT JOIN Vehicles ON People.ID = Vehicles.person_id
WHERE
Vehicles.person_id IS NULL
答案 0 :(得分:1)
joins
方法始终执行INNER JOIN
,但原始SQL查询使用LEFT JOIN
。
scope :person_has_no_vehicle, -> { joins("LEFT OUTER JOIN vehicles ON vehicles.person_id = people.id").where('Vehicles.person_id IS NULL')}