加入三个相关表格中的数据

问题描述 投票:0回答:1

在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

我的第一个查询出了什么问题?

sql postgresql join
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.