2

我有这个 MySQL 查询,看起来很简单:

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

我在这里要做的只是计算所有未读取的 PM(“读取”列中没有“1”)。如果有,查询可以正常工作,但是当没有任何行满足该条件时,它什么也不返回。

我花了最后一个小时寻找解决方案,但它似乎真的很奇怪,它以这种方式工作。它应该只在回显“pms”时打印“0”。

4

4 回答 4

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;
于 2012-06-05T10:08:09.710 回答
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
于 2012-06-05T09:52:11.143 回答
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
于 2012-06-05T09:52:30.507 回答
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

于 2012-06-05T09:53:13.047 回答