从表中计算行数

时间:2016-04-22 08:10:32

标签: mysql sql count rows

我有问题。这似乎很容易解决,但事实上我不知道它为什么不起作用!

我有两张桌子:

HOSTS(id, hostgroup_id)
HOSTGROUPS(id, name)

使用这些插入的行:

HOSTS
________________________
id    |    hostgroup_id
________________________
1     |    1
2     |    1
3     |    2
4     |    NULL         -- a host can have no hostgroup
________________________


HOSTGROUPS
________________________
id    |    name
________________________
1     |    ARM
2     |    Spark
3     |    Pyro
________________________

有了这个,我只想计算每个主机组中的主机数量。 这是我的SQL查询:

SELECT HG.name, COUNT(H.id) AS count
FROM HOSTS H, HOSTGROUPS HG
WHERE H.hostgroup = HG.id
UNION DISTINCT
SELECT HG.name, 0 AS count
FROM HOSTS H, HOSTGROUPS HG
WHERE (H.hostgroup = HG.id) = FALSE

这是我的结果:

_____________________
name     |     count
_____________________
ARM      |     2     -- OK
Spark    |     0     -- NOPE, INTENDED 1
Pyro     |     0     -- OK
ARM      |     0     -- NOPE, DUPLICATED ROW
_____________________

最后,这就是我在等待的东西:

_____________________
name     |     count
_____________________
ARM      |     2
Spark    |     1
Pyro     |     0
_____________________

感谢您的回答! :)

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT hg.name,
(SELECT COUNT(*)
FROM HOSTS h
WHERE h.hostgroup_id = hg.id)
FROM HOSTGROUPS hg

答案 1 :(得分:1)

我认为你可以通过

使用左连接
SELECT HG.name, COUNT(*) AS count
FROM HOSTS H 
LEFT JOIN  HOSTGROUPS HG ON ( H.hostgroup = HG.id)
GROUP BY HG.name;

答案 2 :(得分:1)

SELECT HG.name, COUNT(H.id) AS count
FROM HOSTS H, HOSTGROUPS HG
WHERE H.hostgroup = HG.id(+)
group by H.id;

希望这有帮助