MySQL:当所有字段都为NULL时,如何返回空记录?

时间:2013-03-07 18:29:03

标签: mysql sql null

情况1:

SELECT SUM(mark) AS totalMark, userID, credit
FROM users, marks
WHERE marks.receiverID = users.userID
AND userID = '2'

它会返回

totalMark   userID  credit
---------------------------
0           2       0.0


这很好,没问题。但情况如下2:

SELECT SUM(mark) AS totalMark, userID, credit
FROM users, marks
WHERE marks.receiverID = users.userID
AND userID = '-1'

结果:

totalMark   userID  credit
---------------------------
NULL        NULL    NULL


但我想要的是什么都没有(没有找到记录)。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

当您使用像SUM()这样的聚合函数时,查询将被绑定返回一行。但由于它没有总和值,因此总和的结果是不确定的。

您可以通过以下方式解决此问题:

SELECT * FROM (
    SELECT SUM(mark) AS totalMark, userID, credit
    FROM users, marks
    WHERE marks.receiverID = users.userID
    AND userID = '-1'
) t
WHERE t.totalMark IS NOT NULL;