PG 查询 select 并在 rails 中分组 4
PG query for select and group in rails 4
我正在学习 join
table 的关联,并同时触发 select
和 group
查询。假设我有这样的数据库:
订单:
#has_many :items
id , title , description
项目数:
#belongs_to :order
#belongs_to :product
id , order_id , name , product_id , cost
现在我想列出商品 table 中总数量 order_id 的所有订单的标题。
例如:
Order_title_1 => 5 (count of order_id )
我试过这个查询但给出了错误:我知道它不正确
Item.joins(:orders).select("orders.id, orders.title, SUM(items.order_id) as total").group("order_id")
正如您在 postgresql 中一样,SELECT
子句中出现的列必须出现在 group by 子句中,但您在 [=14] 中使用的列除外=]聚合函数。但就您而言,情况并非如此。尝试将代码编写为:
Item.joins(:order)
.select("orders.id, orders.title, SUM(items.order_id) as total")
.group("orders.id, orders.title")
我正在学习 join
table 的关联,并同时触发 select
和 group
查询。假设我有这样的数据库:
订单:
#has_many :items
id , title , description
项目数:
#belongs_to :order
#belongs_to :product
id , order_id , name , product_id , cost
现在我想列出商品 table 中总数量 order_id 的所有订单的标题。 例如:
Order_title_1 => 5 (count of order_id )
我试过这个查询但给出了错误:我知道它不正确
Item.joins(:orders).select("orders.id, orders.title, SUM(items.order_id) as total").group("order_id")
正如您在 postgresql 中一样,SELECT
子句中出现的列必须出现在 group by 子句中,但您在 [=14] 中使用的列除外=]聚合函数。但就您而言,情况并非如此。尝试将代码编写为:
Item.joins(:order)
.select("orders.id, orders.title, SUM(items.order_id) as total")
.group("orders.id, orders.title")