从多个左连接获取计数的正确方法

时间:2017-07-12 09:05:39

标签: mysql sql count left-join

我正在尝试构建一个查询,它将从一个表中提取所有列,并从另一个相关表中添加一些计数,使用左连接从该表中查找与初始表中每列相关的项目。

到目前为止,我有这个:

SELECT table1.*,
       count(table2_c1.ID) as column1_count,
       count(table2_c2.ID) as column2_count
from table1
left join (select * from table2
           where table2.COLUMN_1 = 1) as table2_c1
    on table1.ID = table2_c1.TABLE1_ID
left join (select * from table2
           where table2.COLUMN_2 = 1) as table2_c2
    on table1.ID = table2_c2.TABLE1_ID
group by table1.ID
having ANOTHER_COLUMN = 1;

但这需要大约5秒的时间来执行,而且我没有添加任何接近最终语句将包含的计数数量。有没有更好的方法呢?我为这个问题的解释很糟糕道歉,我对SQL很新。

1 个答案:

答案 0 :(得分:0)

无需进行双连接,而是使用case表达式来进行条件聚合:

SELECT table1.*,
       count(case when table2.COLUMN_1 = 1 then 1 end) as column1_count,
       count(case when table2.COLUMN_2 = 1 then 1 end) as column2_count
from table1
left join table2
    on table1.ID = table2.TABLE1_ID
group by table1.ID
having ANOTHER_COLUMN = 1;