tags:

views:

131

answers:

4

Is there a better way of doing this ?

SELECT
  (SELECT count(*) FROM `tbl` WHERE `status` = 0) as 'text1',
  (SELECT count(*) FROM `tbl` WHERE `status` > 0) as 'text2'

text1 and text2 are headers.

+2  A: 

How about

select sum(if(status=0,1,0)) as zeros, 
       sum(if(status>0,1,0)) as greater 
from tbl;

Might not necessarily be better, but it's a useful idiom to have in your mental arsenal!

Paul Dixon
This was just what I was looking for. ThanksBye-bye to ugly sub-selects...
Kim
Ugly sub-selects may be ugly but per-row functions will not scale well. Your original solution is almost certainly better from a performance perspective.
paxdiablo
It doesnt matter as I frequently delete rows no longer valid, so the table is always small.
Kim
A: 

This gives you a different output, but sorta works:

SELECT `status` > 0 AS 'stat', COUNT( * )
FROM `tbl`
GROUP BY stat

Output:

stat | COUNT(*)
-------------------------------
 0   | (count where status = 0)
 1   | (count where status > 0)
nickf
+1  A: 

I vote for using two different queries for the sake of simplicity and improved code readability. There isn't much benefit of using a clever hack to combine the queries, when you can achieve the same result and more readable code by having two queries,

Click Upvote
A: 

Here's another way:

SELECT
  COUNT(NULLIF(`status` = 0, 0)),
  COUNT(NULLIF(`status` > 0, 0))
FROM `tbl`
nickf