【问题标题】:Find all records who has exactly 3 associated records in another table查找在另一个表中恰好有 3 个关联记录的所有记录
【发布时间】:2015-10-21 06:57:31
【问题描述】:

我有以下型号

class Price < ActiveRecord::Base
  has_many :line_items
  ...

class AdvancedPriceLineItem < ActiveRecord::Base
  belongs_to :price
  ....

我想查找所有 Price 记录恰好有 3 个 LineItem 引用它

如何做到这一点?

非常感谢

【问题讨论】:

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


    【解决方案1】:

    您可以尝试这种方式进行活动记录

    Price.includes(:line_items).group("line_items.price_id").having("count(*) = 3")
    

    【讨论】:

    • 这会引发以下错误PG::UndefinedTable: ERROR: missing FROM-clause entry for table "line_items"
    • 是的,您需要在查询中使用正确的关联名称和表名称,我只是根据您的模型使用了这个名称。否则把你的模型和架​​构放在这里
    • 用关联和名称更新了帖子
    • @Tarlen 这个查询是正确的根据关联名称和它在mysql 中的工作根据你的错误我认为如果你的表名是advanced_price_line_items 然后用group("advanced_price_line_items.price_id") 替换组它取决于你表名
    • 不,它们应该是正确的。我可以打电话给Price.last.line_items,它可以工作
    【解决方案2】:

    给你..

    select * from
    price where  id in (select price_id
    from LineItem
    group by  price_id
    having count(*) =3
    )
    

    【讨论】:

    • 如果价格表中的 id 等同于 LineItem 中的其他列,则在内部查询中相应更改
    • @anwar_hell is group by id 在这里工作??我认为在订单项表中id 是 uniq。您需要将 foreign_key 用于非主要组
    • @vishal.. 如果 id 是唯一的,则将其替换为其他的 price_id
    • 从子查询的选择列表中删除“,count(id)”。并执行 IN 而不是 = 子查询。
    • 更正了查询,但使用 = 或 in 与生成相同计划的解析器没有太大区别...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2011-10-23
    • 2020-06-20
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多