我想计算每个conversations
关闭了多少user
,以及每个messages
写了多少user
。
user
有许多conversations
conversations
有许多messages
message
可以属于user
这是我有点远的查询
select a.id, u.display_name, count(c.id) as closed, count(m.id) as replied
from apps a
left join app_users au on au.app_id = a.id
left join users u on u.id = au.user_id
left join conversations c on c.app_id = a.id and c.closed_by_id = u.id
left join messages m on m.conversation_id = c.id and m.user_id = u.id
group by a.id, u.id
order by closed desc
当我没有加入消息并只计算已关闭的对话时,它工作正常。加入邮件时,closed
和replied
列的编号完全相同(并且两者都不正确)
有什么想法吗?
答案 0 :(得分:1)
您可以在加入之前在子查询中进行计数:
select a.id, u.display_name, c.closed, m.replied
from apps a
left join app_users au on au.app_id = a.id
left join users u on u.id = au.user_id
left join lateral (
select id, count(*) as closed
from conversations
where closed_by_id = u.id) c on c.app_id = a.id
left join lateral (
select count(*) as replied
from messages
where user_id = u.id) m on m.conversation_id = c.id
order by c.closed desc;
答案 1 :(得分:0)
快速而肮脏的解决方案是使用count(distinct)
:
select a.id, u.display_name,
count(distinct c.id) as closed, count(distinct m.id) as replied
这在许多情况下都有效。但如果有很多"关闭"并且"回复",然后中间计算可能非常大,影响性能。如果这是一个问题,那么在联接之前预先聚合结果就是解决方案。