gpt4 book ai didi

sql - 如何找到既有跳蚤又有蜱虫的用户 :through pets?

转载 作者:行者123 更新时间:2023-12-04 14:08:43 26 4
gpt4 key购买 nike

好的,我最近有great answers to a question about how to do some sub-selects in an activerecord query .我现在有一个更复杂的情况,我无法弄清楚。

我想在 3 个与 :through 具有多对一关系的表中进行搜索,例如

class User << ActiveRecord::Base
has_many :pets
has_many :parasites, :through => :pets
end

class Pet << ActiveRecord::Base
has_many :parasites
belongs_to :users
end

class Parasite << ActiveRecord::Base
belongs_to :pets
end

现在假设我有一些这样的数据
users

id name
1 Bob
2 Joe
3 Brian

pets

id user_id animal
1 1 cat
2 1 dog
3 2 cat
4 3 dog

parasites

id pet_id bug
1 1 tick
2 2 flea
3 3 tick
4 3 flea
5 4 tick

我想要做的是创建一个事件记录查询,该查询将返回一个用户,该用户的宠物既有蜱又有跳蚤(即用户 2 - 乔)

这远远超出了我的 activerecord 和 sql 技能,我什至不会费心向您展示我迄今为止的拙劣尝试。

最佳答案

这与上一个问题几乎相同,您只需要在子选择上更深入地挖掘一个级别:

User.where('id IN (SELECT user_id FROM pets WHERE
id IN (SELECT pet_id FROM parasites WHERE bug = ?) AND
id IN (SELECT pet_id FROM parasites WHERE bug = ?))', 'flea', 'tick')

关于sql - 如何找到既有跳蚤又有蜱虫的用户 :through pets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6701800/

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