0

这些表是:

Orders
-----------
user_id
state


Items
-----------
order_id
product_id
total

Products
----------
user_id


Users
---------
name
email

关系如下:

User
has_many :products

Order
has_many :items
belongs_to :users

Product
has_many :items
belongs_to :user

Item
belongs_to :items

我想获得每个拥有该产品的用户的 items.total 的总和

我目前有以下 SQL 语句:

SELECT *, SUM(items.total) as totalprice 
FROM "orders" 
INNER JOIN "items" ON "items"."order_id" = "orders"."id"
INNER JOIN "products" ON "products"."id" = "items"."product_id"
INNER JOIN "users" ON "users"."id" = "products"."user_id"
WHERE "orders"."state" = 'complete'
GROUP BY users.id

或者

Order.complete.joins(:items => {:product => :user}).select("*, SUM(items.total) as totalprice").group('users.id')

以上不起作用。我觉得这应该很容易。

4

1 回答 1

2

在 group by 查询中,您需要包括所有未在 group by 子句中聚合的列。如果您将查询更改为此,您可能会有更好的运气

SELECT users.id, SUM(items.total) as totalprice 
FROM "orders" 
INNER JOIN "items" ON "items"."order_id" = "orders"."id"
INNER JOIN "products" ON "products"."id" = "items"."product_id"
INNER JOIN "users" ON "users"."id" = "products"."user_id"
WHERE "orders"."state" = 'complete'
GROUP BY users.id

如果您想要输出中的更多列,请将它们添加到选择行和按行分组

于 2013-04-24T09:13:39.560 回答