gpt4 book ai didi

sql - 如何简单地加入 Rails 中的 n 对 n 关联?

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:42 25 4
gpt4 key购买 nike

我有三个表:userslocationslocations_users,关联如下:

user has_many locations_users
user has_many locations :through => locations_users

location has_many locations_users
location has_many users :through => locations_users

我如何在一次查询中找到加入到 location_id = 5 的所有用户?

如有任何帮助,我们将不胜感激。

最佳答案

您可以使用 LEFT OUTER JOIN。它从左表中获取所有数据,并从右表中获取匹配数据(如果存在)(如果不存在,则连接列为空):

User
.joins('LEFT OUTER JOIN locations_users ON locations_users.user_id = users.id')
.where('locations_users.id IS NULL OR locations_users.location_id = ?', 5)
.all

然而:

  • 此查询使用 join,它在大表上的性能可能很差(也许两个查询会执行得更快 - 测试一下!)
  • 为了获得更好的性能,请确保在连接列上设置索引

关于sql - 如何简单地加入 Rails 中的 n 对 n 关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38645143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com