坚持一个简单的查询 - OUTER JOIN

时间:2013-03-19 15:48:20

标签: mysql outer-join

我有一个简单的查询,但我被卡住了,我真的无法弄清楚如何做到这一点。 进一步来说: 表Allarmi有很多条目,我显示所有条目都按Allarmi.IDComponente

分组

类似这样的事情

SELECT * 
FROM ALLARMI AS ALLARMI
WHERE ID_CELLA = 1
GROUP BY ID_Componente

我只需要在此表中添加COUNT列,例如

(SELECT COUNT( * ) 
FROM allarmi
WHERE isAttivo = 1
GROUP BY id_componente)

但即使COUNT0

,我也想展示NULL

我该怎么办? 提前致谢

1 个答案:

答案 0 :(得分:1)

假设表Componenti定义了组件,并且您希望从allarmi获取每个组件的记录数,那么您真正想要做的是从Componenti中选择组件,在allarmi

上添加LEFT OUTER JOIN
SELECT COMPONENTI.ID_Componente, COUNT(ALLARMI.ID_Componente)
FROM COMPONENTI
LEFT OUTER JOIN ALLARMI ON
   -- insert your join here!
   -- maybe COMPONENTI.ID_Componente= ALLARMI.ID_Componente?
   -- add any query for this table here as well.
   AND ALLARMI.ID_Cella = 1
GROUP BY COMPONENTI.ID_Componente