在下面的设置中,客户通过标记获得了很多标签。
class Customer
has_many :taggings
has_many :tags, through: :taggings
end
class Tagging
belongs_to :tag
belongs_to :customer
end
我尝试在 Rails 中使用 postgres 执行的查询是查找至少有一个标签但没有标签 A 或 B 的所有客户。
由于有数以万计的客户,因此需要考虑性能。
最佳答案
请尝试以下查询。
Customer.distinct.joins(:taggings).where.not(id: Customer.joins(:taggings).where(taggings: {tag_id: [tag_id_a,tag_id_b]}).distinct )
解释。
联接将触发内部联接查询,并确保您只获取那些至少有一个与之关联的标签的客户。
where.not
将处理您的附加条件。
希望这对您有所帮助。
关于ruby-on-rails - 查找至少具有一个关联的记录,但排除任何关联都符合条件的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384683/