Jack
Jack

Reputation: 9784

Complex MySQL COUNT query

Evening folks,

I have a complex MySQL COUNT query I am trying to perform and am looking for the best way to do it.

What I have been trying to do is this, using a combination of PHP and MySQL to bridge the gap where SQL (or my knowledge) falls short:

First, select a COUNT of the number of incomes associated with each reference:

SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `income`.`status` =  0
GROUP BY `reference_id` 

Next, having used PHP to generate a WHERE IN clause, proceed to COUNT the number of confirmed references from these:

SELECT `reference_id`, COUNT(status) AS status_count
FROM (`income`)
WHERE `reference_id` IN ('8469', '78969', '126613', ..... etc 
AND status = 1
GROUP BY `reference_id` 

However this doesn't work. It returns 0 rows.

Any way to achieve what I'm after?

Thanks!

Upvotes: 2

Views: 701

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562328

In MySQL, you can SUM() on a boolean expression to get a count of the rows where that expression is true. You can do this because MySQL treats true as the integer 1 and false as the integer 0.

SELECT `reference_id`, 
  SUM(`status` = 1) AS `validated_count`, 
  COUNT(*) AS `total_count` 
FROM `income`
GROUP BY `reference_id` 

Upvotes: 3

Related Questions