2012-06-05 96 views
2

我有這樣的MySQL查詢,似乎很簡單:MySQL的計數應該返回0,沒有返回

SELECT users.nick, users.id, COUNT(pm.id) AS pms 
FROM users LEFT JOIN pm ON users.id = pm.touser 
WHERE users.id = :id AND pm.read = 0 
GROUP BY users.id 

我想在這裏做的是簡單地計算所有未讀的PMS(沒有「閱讀」欄中的「1」)。如果有的話,查詢工作正常,但是當沒有任何行滿足該條件時,它不返回任何內容。

我花了最後一個小時尋找解決方案,但看起來很奇怪,它以這種方式工作。它只能在回顯「pms」時打印「0」。

回答

1

簡單:

SELECT users.nick, users.id, COUNT(pm.id) AS pms 
FROM users LEFT JOIN pm ON (users.id = pm.touser AND pm.read = 0) 
WHERE users.id = :id 
GROUP BY users.id; 
+0

它的工作,謝謝! –

0

試試這個

SELECT nick,id, COUNT(id) AS pms 
FROM users LEFT JOIN (Select touser as id from pm where read =0) as pms1 
WHERE id = :id GROUP BY id 
0

嘗試扭轉表順序:

SELECT users.nick, users.id, COUNT(pm.id) AS pms 
FROM pm 
LEFT JOIN users 
ON users.id = pm.touser 
WHERE users.id = :id AND pm.read = 0 
GROUP BY users.id 
0
SELECT users.nick, users.id, COUNT(pm.id) AS pms 
FROM users 
LEFT JOIN 
     pm 
ON  (pm.touser, pm.read) = (users.id, 0) 
WHERE users.id = :id 
GROUP BY 
     users.id 

pm.read = 0應該去ON條款。

WHERE子句過濾掉所有NULL由於pm錯過而產生的值。