gpt4 book ai didi

sql - postgresql:选择所有关联记录都匹配条件的记录

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:38 25 4
gpt4 key购买 nike

我有:

class A < ActiveRecord::Base
has_many :abs
has_many :bs, through: :abs
end

class AB
belongs_to :a
belongs_to :b
end

class B < ActiveRecord::Base
has_many :abs
has_many :as, through: :abs
# and has boolean db field :matches
end

所以我想为 A 实现一个范围,它检索 As,其中 all 它与 Bs matches=true 相关联。通常,我会做类似的事情:

A.joins(:bs).where(bs: { matches: true })

但这将检索 As,其中至少一个 b 符合条件,而不是所有

想法?

最佳答案

相反,我会查找包含零个 matches: false 实例的记录。我可能会使用子查询,例如...

A.joins(:bs).where('(select count(*) from bs where matches = false) = 0')

但可能有更 ActiveRecord 的方式来做这件事。

关于sql - postgresql:选择所有关联记录都匹配条件的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152499/

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