MySQL multiple count in single table with different where clause
October 23, 2011 1 Comment
Sometimes we want to do multiple count task on specific table.
Here’s the worst we could do, we doubling the job, pathetic
$q1 = mysql_query( "select count(column) from table where column = 'x' "); echo( mysql_result( $q1, 0 ) ); $q2 = mysql_query( "select count(column) from table where column = 'y' "); echo( mysql_result( $q2, 0 ) );
Then we thought this could be better, using subquery
select (select count(column) from table where column = 'x') as count1, (select count(column) from table where column = 'y') as count2 from table
that’s also pretty stupid and wasting.
but there’s another idea..
select sum(if(column='x',1,0)) as count1, sum(if(column='y',1,0)) as count2, from table
rather than use where clause, we could do if statement that add +1 when meet condition – then sum it
Great, it was since three days that i was searching this trick and finally I found it… and it works!!