如何包含MySQL COUNT为0的行?

时间:2012-01-12 16:20:20

标签: mysql count

我正在使用以下查询返回如下结果:

SELECT  subnets.subnet_id , INET_NTOA(  subnets.address ) AS inet_address, subnet_masks.hosts, COUNT(addresses.STATUS) AS status_count
FROM subnets
LEFT JOIN subnet_masks ON subnets.mask_id = subnet_masks.mask_id
LEFT JOIN addresses ON subnets.subnet_id = addresses.subnet_id
WHERE addresses.status = 'allocated'
GROUP BY subnet_id      
ORDER BY subnets.address



subnet_id   inet_address    hosts   status_count
91          10.10.10.0      65534   3
71          192.168.1.0     254     6
90          192.168.10.0    254     1

但是我希望它返回计数为0的行,就像这样:

subnet_id   inet_address    hosts   status_count
91          10.10.10.0      65534   3
76          172.128.0.0     254     0
71          192.168.1.0     254     6
90          192.168.10.0    254     1

我读到这可能是我的JOIN的一个问题,所以我尝试了很多不同的,我得到了相同的结果。有谁知道我做错了什么?

4 个答案:

答案 0 :(得分:9)

您的WHERE子句正在过滤记录...将其移至LEFT JOIN以解决问题:

SELECT  subnets.subnet_id , INET_NTOA(  subnets.address ) AS inet_address, subnet_masks.hosts, COUNT(addresses.STATUS) AS status_count
FROM subnets
LEFT JOIN subnet_masks ON subnets.mask_id = subnet_masks.mask_id
LEFT JOIN addresses ON subnets.subnet_id = addresses.subnet_id AND addresses.status = 'allocated'
GROUP BY subnet_id      
ORDER BY subnets.address

答案 1 :(得分:0)

请改为尝试:

SELECT  subnets.subnet_id , INET_NTOA(  subnets.address ) AS inet_address,  
    subnet_masks.hosts, COUNT(addresses.STATUS) AS status_count
FROM subnets
LEFT JOIN subnet_masks ON subnets.mask_id = subnet_masks.mask_id
LEFT JOIN addresses ON subnets.subnet_id = addresses.subnet_id
    and addresses.status = 'allocated'
GROUP BY subnet_id      
ORDER BY subnets.address

答案 2 :(得分:0)

您的where子句指定address.status ='assigned'但是status_count等于0的行没有地址,因此不能具有此状态。

答案 3 :(得分:0)

你的左连接错了它应该是这样的

SELECT  subnets.subnet_id , INET_NTOA(  subnets.address ) AS inet_address, subnet_masks.hosts, COUNT(addresses.STATUS) AS status_count
FROM subnets
LEFT JOIN subnet_masks ON subnets.mask_id = subnet_masks.mask_id
LEFT JOIN addresses ON subnets.subnet_id = addresses.subnet_id AND addresses.status = allocated'
GROUP BY subnet_id      
ORDER BY subnets.address