作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好的,我最近有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
最佳答案
这与上一个问题几乎相同,您只需要在子选择上更深入地挖掘一个级别:
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/
我是一名优秀的程序员,十分优秀!