2012-01-12 110 views
2

我使用下面的查詢返回如下結果:如何包含MySQL COUNT爲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 
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問題,所以我嘗試了許多不同的方法,並得到相同的結果。有誰知道我做錯了什麼?

回答

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 
+0

感謝解釋:)這完美的作品 – Bernard 2012-01-12 16:29:38

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 
0

你的where子句指定address.status =「分配」,但與status_count等於0的行沒有地址,因此不能有這樣的狀態。

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 
相關問題