2

Situation 1:

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

It will return

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



And it is very good, no problem. But here is the situation 2:

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

Result:

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


But what I want is return nothing (no record found). Anyone could help me?

1
  • Anytime you use an aggregate you will get at least one row. Commented Mar 7, 2013 at 18:32

1 Answer 1

2

When you use an aggregate function like SUM(), the query is bound to return a row. But since it's summing no values, the result of the sum is undefined.

You could work around this in the following way:

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.