【问题标题】:Fetch records from a table based on the condition in associated table根据关联表中的条件从表中获取记录
【发布时间】:2015-03-13 06:52:33
【问题描述】:

我有两个模型 School 和 Expense 学校有很多费用,Expense 有一个名为 cost 的属性

我试图只获取那些费用成本大于某个值的学校,比如 1000,我尝试了这个查询

School.includes(:expenses).where("lower(schools.name) LIKE '%a%' and expenses.cost >= 1000").select('*').from('schools, expenses')

这个查询的问题是如果学校有多个费用大于 1000,它返回重复值,我想要的只是基于条件的唯一学校。

请帮忙!

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord rails-activerecord


    【解决方案1】:
    School.
    joins(:expenses).
    where("lower(schools.name) LIKE ?", "%a%"). # part of the code you shared
    where("expenses.cost > ?", 1_000).
    group("schools.id")
    

    【讨论】:

    • 如果每个学校都没有费用怎么办?
    • 由于这是一个内部连接,这些学校将被忽略。在我们的例子中,这绝对没问题,因为我们只想要费用大于某个值的学校。如果您仍然想在查询过滤它们之前包含这些学校(无论出于何种原因),您可以使用如下外部连接:School.join("LEFT OUTER JOIN expenses ON expenses.school_id = schools.id").where(conditions).group("schools.id")
    • 感谢您的帮助!
    • 没问题。不过,我上面的评论中的小错误。方法是joins 而不是join。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多