gpt4 book ai didi

sql - 根据一组相关记录的条件获取记录

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

我有两个类(class)

class Patient < ActiveRecord::Base
belongs_to :camp
has_many :vaccinations
end

class Vaccination < ActiveRecord::Base
belongs_to :patient
end

每个疫苗接种都有名为 vaccine_id 的成员。 “完整”疫苗接种包括一组(比方说)6 种不同的疫苗,:names = {A,B,C,D,E,F}。

患者接种了很多疫苗,我想要一份所有接受“完整”疫苗接种的患者的报告。我可以使用 SQL 或 ActiveRecord 查询来获取此患者列表吗?

最佳答案

也许是这样的:

# in patient.rb
scope :with_completed_vaccinations, ->(number) {
joins(:vaccinations).group('patients.id').
having('COUNT(vaccinations.name) >= ?', number)
}

有了这个scope,您就可以编写如下查询:

Patient.with_completed_vaccinations(6)

关于sql - 根据一组相关记录的条件获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29786317/

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