【问题标题】:How to separate objects based on column value and retrieve and retrieve the first object of each group?如何根据列值分离对象并检索和检索每个组的第一个对象?
【发布时间】:2016-12-30 20:11:53
【问题描述】:

我是一个相当新的编程人员,我无法为我遇到的问题找到答案。我正在使用活动记录、rails 和 sqlite3,并且我有一个名为 Unit 的模型。这些单位有几列类别、已售出、颜色等,还有一个 product_code,它对于前面提到的列中的每个唯一值组合都是唯一的。我不能做的是根据它们拥有的 product_code 分离所有单元,然后检索每种类型的对象(第一个或任何一个)。单位还需要在已售列中具有错误值。我第一次尝试:

Unit.where(sold:false).select(:product_code).distinct

但这只会给我不同的代码:

#<ActiveRecord::Relation [#<Unit id: nil, product_code: "MONMJARD327">, 
#<Unit id: nil, product_code: "LAPEJARD327">, 
#<Unit id: nil, product_code: "ESTXJARD327">, 
#<Unit id: nil, product_code: "COSGJARD327">,
#<Unit id: nil, product_code: "BOLAJARD327">, 
#<Unit id: nil, product_code: "FUNIJARD327">, 
#<Unit id: nil, product_code: "CARMJARD327">, 
#<Unit id: nil, product_code: "MOCEJARD327">, 
#<Unit id: nil, product_code: "COJGJARD327">, 
#<Unit id: nil, product_code: "RELG">, ...]>

问题是我需要检索每个不同组的列值,以便形成一个表。然后我尝试了这个:

Unit.where(sold:false).group(:product_code)

这在开发中运行良好:

[#<Unit id: 104, product_code: "BOLAJARD327", sold: false, category_id: 16, remission_id: nil, created_at: "2016-08-23 20:30:13", updated_at: "2016-08-23 20:30:13", fabric_id: 2, color_id: 1, pattern_id: 13, batch_id: nil, profit: nil, date_sold: nil, store_id: nil>, 
#<Unit id: 106, product_code: "CARMJARD327", sold: false, category_id: 11, remission_id: nil, created_at: "2016-08-23 20:30:13", updated_at: "2016-08-23 20:30:13", fabric_id: 2, color_id: 1, pattern_id: 13, batch_id: nil, profit: nil, date_sold: nil, store_id: nil>, etc.]

但在开发中我使用 PosgresSQL,这会产生错误:

PG::GroupingError: ERROR:  column "units.id" must appear in the GROUP BY clause or be used in an aggregate function

是否有更好的方法来进行此选择并按预期检索对象?

提前致谢!

【问题讨论】:

  • 进入 PostgreSQL 的 SQL 查询是什么?
  • 这是我可以从 heroku 日志中检索到的内容: : SELECT "units".* FROM "units" GROUP BY "units"."product_code"): LINE 1: SELECT "units".* FROM "units" GROUP BY "units"."product_code
  • 这个查询永远不会在 PostgreSQL 中工作。 PostgreSQL 严格要求选定列和分组列之间的一致性。您不能选择所有列并仅按一列分组。使用 .select(:product_code) 之类的东西加上聚合。

标签: ruby-on-rails postgresql activerecord sqlite


【解决方案1】:

不完全确定我理解您在此处尝试做什么,但如果您想要包含产品代码的未售出单元的 ActiveRecord 关系,您可以这样做:

Unit.where(sold: false).select(:product_code)
# which returns
=> #<ActiveRecord::Relation [#<Unit id: nil, product_code: "ESTXJARD327">, #<Unit id: nil, product_code: "BOLAJARD327">]>

然后选择第一个,您可以执行以下操作:

Unit.where(sold: false).select(:product_code).first

如果您有多个具有相同product_code 的单元,您可以将它们组合在一起:

Unit.where(sold: false).select(:product_code).group(:product_code)

同样,您可以通过附加 .first 在此处选择第一个条目

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2021-11-05
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2020-11-28
    相关资源
    最近更新 更多