我上面有一个表和用户,我有这个查询
获取传入和传出
SELECT username ,
( Select count(*) from calls where type = 'incoming' and user_id = user.id) as incoming,
( Select count(*) from calls where type = 'outgoing' and user_id = user.id) as outgoing
from user
join calls on user.id = calls.user_id
group by user_id
我得到了正确的数据但有更好的方法来进行此查询吗?
这是查询的结果
答案 0 :(得分:1)
只需使用条件聚合:
select u.username,
sum(case when c.type = 'incoming' then 1 else 0 end) as incoming,
sum(case when c.type = 'outgoing' then 1 else 0 end) as outgoing
from user u join
calls c
on u.id = c.user_id
group by u.username;
请注意其他更改:
group by
列与select
列匹配。