简体   繁体   English

Rails 4左外部联接问题返回错误记录

[英]Rails 4 left outer join issue returning wrong records

I have 2 tables: appointments and doors. 我有2张桌子:约会和门。 Door has one appointment and appointment belongs to a door. 门有一个约会,约会属于一门。 The appointments table have the door_id. 约会表具有door_id。

The query I wrote is: 我写的查询是:

scope :not_in_appointments, -> { joins("left outer join appointments on appointments.door_id = doors.id") }

ISSUE: The scope is still returning the doors that are in the appointments table. 问题:范围仍在返回约会表中的门。

GOAL: We want to get doors that are NOT in the appointments table. 目标:我们希望获得约会表中未包含的门。

The left outer join is suppose to do that. 假定左外部联接可以这样做。 Can someone please let us know why this query is not working? 有人可以告诉我们为什么这个查询不起作用吗?

Thanks. 谢谢。

效果也一样,在范围内添加了一个额外的where子句:

scope :not_in_appointments, -> { joins("left outer join appointments on appointments.door_id = doors.id").where("appointments.id IS NULL") }

Let try this one 让我们试试这个

scope :not_in_appointments, -> { where("id NOT IN (SELECT door_id FROM appointments)") }

The performance is much better than using 'left outer join' because we are reducing number of redundant records as soon as possible. 该性能比使用“左外部连接”要好得多,因为我们将尽快减少冗余记录的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM