在Postgres中,我有以下4个表
user (
id,
name
);
order(
id,
user_id
)
service(
id,
name
);
order_to_service(
id,
order_id,
service_id
price
);
我想写一个查询来查看用户名,该用户的订单数量以及他在所有订单上花了多少钱 例如:
name amount price
Albert 100 3200
这是我的查询
select u.name , count(o.user_id),sum(ots.price)
from orders o inner join users u on u.id=o.user_id
inner join order_to_service ots on ots.order_id = o.id
where(o.user_id is not null) group by u.name
这是我的结果:
"Аlbert";55;29978
根据此结果,名为Albert的用户有55个订单 但是使用这个查询
select count(*) from orders where user_id = (select id from users where name like 'Albert')
Result is 33
我的第一次查询出了什么问题?
答案 0 :(得分:1)
如果Orders表和Order_to_service表之间的关系是一对多,那么在加入Orders表之前,您需要在Order_to_service表中总结每个订单的价格。试试这个:
select u.name , count(o.user_id),sum(ots.price_tot)
from orders o inner join users u on u.id=o.user_id
inner join ( select order_id, sum(price) as price_tot
from order_to_service
group by order_id ) ots
on ots.order_id = o.id
where (o.user_id is not null) group by u.name