从一个表中选择,从未链接id的另一个表中计数

时间:2017-02-13 06:05:34

标签: mysql

表1

enter image description here

表2

enter image description here

预期产出

打开| 2

待定| 0

关闭| 0

等......

我尝试使用以下查询

SELECT d.status , COUNT(*) num,e.name  FROM table1 d  cross join table 2 e group by name;

导致了

enter image description here

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:4)

您需要左连接。这种类型的连接显示左表中的所有行,即使右表中没有行也存在。

select t2.name, count(t1.id)
from table2 as t2
left join table1 as t1 on t2.name = t1.status
group by t2.name

请注意,您需要在table1的列上聚合,以生成所需的0,因此count(t1.id)。即使count(*)没有行,1也会生成table1

您在查询中的交叉连接只是创建了所涉及的两个表的笛卡尔积,导致左表中的每一行与右表中的每一行连接一次。