我有这个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(“read”col中没有“1”)。如果有,查询工作正常,但当没有任何行满足该条件时,它不返回任何内容。
我花了最后一小时寻找解决方案,但它似乎很奇怪,它以这种方式工作。它只应在回显“pms”时打印“0”。
答案 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;
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
值。