Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL.. Return '1' if a COUNT returns anything greater than 0

Tags:

sql

mysql

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?

like image 441
kimion09 Avatar asked Jun 04 '11 03:06

kimion09


People also ask

Will count (*) ever return NULL?

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.

Does zero count as NULL MySQL?

In MySQL, 0 or NULL means false and anything else means true. The default truth value from a boolean operation is 1 .

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.


1 Answers

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
like image 109
mu is too short Avatar answered Oct 07 '22 12:10

mu is too short