I'm trying to create MySQL query that essentially returns true or false. I'd like to run
SELECT COUNT(id)
FROM comments
WHERE comment_date >= 1306904400
AND user_id = 1
So if the user posted in the forum 10 times this month, I'd like it to return just 1, otherwise I'd like it to return 0 to indicate they haven't.
Is that possible efficiently within SQL?
COUNT never returns null. The following example calculates, for each employee in the employees table, the moving count of employees earning salaries in the range 50 less than through 150 greater than the employee's salary.
In MySQL, 0 or NULL means false and anything else means true. The default truth value from a boolean operation is 1 .
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.
If you don't mind MySQL-specific things then you could use IF
:
select if(count(id) >= 10, 1, 0)
from comments
where comment_date >= 130690440
and user_id = 1
Or MySQL booleans (which are 1 for true and 0 for false):
select count(id) >= 10
from comments
where comment_date >= 130690440
and user_id = 1
If you want to stick to standard SQL, then CASE
is your friend:
select case when count(id) >= 10 then 1 else 0 end
from comments
where comment_date >= 130690440
and user_id = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With