我如何优化我的SQL查询

时间:2017-07-06 02:15:44

标签: sql

enter image description here

enter image description here

我上面有一个表和用户,我有这个查询

获取传入和传出

      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

我得到了正确的数据但有更好的方法来进行此查询吗?

这是查询的结果

enter image description here

1 个答案:

答案 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列匹配。