我是postgresql的新手。我有一个数据库,里面有三个表:Users,Order,Comments。这三个表看起来像这样
Orders Comments
------ --------
ID ID
UserID UserID
Description Details
CreatedOn CreatedOn
我试图获取所有用户的列表以及每个用户订购的订单数量以及每个用户的评论数量。换句话说,查询的结果应如下所示:
UserID Orders Comments
------ ------ --------
1 5 7
2 2 9
3 0 0
...
目前,我正在尝试以下方法:
SELECT
UserID,
(SELECT COUNT(ID) FROM Orders WHERE UserID=ID) AS Orders,
(SELECT COUNT(ID) FROM Comments WHERE UserID=ID) AS Comments
FROM
Orders o,
Comments c
WHERE
o.UserID = c.UserID
这是进行此类查询的正确方法吗?或者有人可以从绩效角度提供更好的方法吗?
答案 0 :(得分:1)
select
id, name,
coalesce(orders, 0) as orders,
coalesce(comments, 0) as comments
from
users u
left join
(
select userid as id, count(*) as orders
from orders
group by userid
) o using (id)
left join
(
select userid as id, count(*) as comments
from comments
group by userid
) c using (id)
order by name
答案 1 :(得分:0)
通常的方法是使用外部联接到另外两个表,然后按id
(和名称)分组
select u.id,
u.name,
count(distinct o.id) as num_orders,
count(distinct c.id) as num_comments
from users u
left join orders o on o.userId = u.id
left join comments c on c.userId = u.id
group by u.id, u.name
order by u.name;
这可能比你的方法更快。但是Postgres'查询优化器非常智能,我已经看到两种解决方案在性能上基本相同的情况。
您需要对数据进行测试,并查看执行计划,以找出哪一个更有效。