n00b questioner here. I’m trying to do a query that checks if the most recent activity is within the last 24 hours. I technically can get the result I want, but the inequality in my case statement has to be in the opposite direction as would make sense to me. Here’s my query:
SELECT sqs.registration_id,
MAX(sqs.completed_at) AS 'most recent activity',
DATE_SUB(NOW(), INTERVAL 1 DAY) AS 'one day ago',
'recent activity?' = CASE
WHEN MAX(sqs.completed_at) <
DATE_SUB(NOW(), INTERVAL 1 DAY)
THEN 1
ELSE 0
END
FROM student_quiz_states sqs
WHERE sqs.score = 100
GROUP BY sqs.registration_id
Here’s an example result:
XXXXX 2011-08-02 16:23:53 2011-12-05 00:06:05 0
This user did not have activity in the last 24 hours, so the last value returns 0, as I want it to.
However, that doesn’t make any sense to me. Shouldn’t the case statement return a 1, since the first datetime is much earlier than one day ago? It would make sense to me if my desired results were returned when my when_clause contained a > instead of a <.
Any explanations would be appreciated.
The problem is that your query contains
'recent activity?' = CASE ... ENDwhere it should haveCASE ... END AS 'recent activity?'. The former is an equality-test rather than an expression with an alias. The reason for the seemingly “inverted” behavior is that, since theCASEexpression is numeric (it evaluates to0or1), MySQL performs a numeric equality-test, by converting'recent activity?'to 0.0 (detailed rules here), such that'recent activity?' = CASE ... ENDis true when theCASEexpression gives0and false when it gives1. Since MySQL represents true as1and false as0, the end result is the opposite of what you were expecting.(Note: An earlier version of this answer, while making the same basic point about equality-tests vs. aliases, and about false and true being
0and1, was vague/confused in other respects, since I didn’t recognize that the DBMS was MySQL, and was not aware that some DBMSes allow single-quotes to be used when quoting aliases. So if some of the comments above and below seem a bit strange, it’s because they’re referring to that version. The current state of the answer is thanks in large part to those comments.)