views:

62

answers:

3

Hi,

I am trying to perform a query which groups a set of data by an attribute called type_id.

SELECT
vt.id AS voucher_type,
COALESCE(COUNT(v.id), 0) AS vouchers_remaining
FROM
vouchers v
INNER JOIN voucher_types vt
ON vt.id = v.type_id
WHERE
v.sold = 0
GROUP BY vt.id

What I want in the result is the type_id and the number of unsold products remaining for each type. This is working OK provided that there is at least one left, however if there is a zero count row, it is not returned in the result set.

How can I set up a dummy row for those types which do not have any corresponding rows to count?

Any advice would be greatly appreciated.

Thanks

A: 

You want an OUTER JOIN (or LEFT JOIN, same difference) instead of an INNER JOIN. That should already do the trick.

Thomas
A: 

Hello!

Because you're doing an INNER JOIN you automatically exclude types with no corresponding vouchers. You need a RIGHT OUTER JOIN.

Also, as far as I can remember, COUNT will always give you an integer, so there is no need for the COALESCE.

Good luck, Alin

Alin Purcaru
COUNT will return the number of non-NULL values found, so its return value can never be NULL. See http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_count
Alin Purcaru
+1  A: 

You'll have to use a LEFT JOIN instead of an INNER JOIN. You start by selecting all voucher_types and then left join to find the count.

SELECT
  voucher_types.id AS voucher_type,
  IFNULL(vouchers_count.vouchers_remaining, 0) AS vouchers_remaining
FROM
  voucher_types
LEFT JOIN
  (
    SELECT
    v.type_id AS voucher_type,
    COUNT(v.id) AS vouchers_remaining
    FROM
    vouchers v
    WHERE
    v.sold = 0
    GROUP BY v.type_id
  ) AS vouchers_count
  ON vouchers_count.voucher_type = voucher_types.id
madgnome
Thanks a lot, that worked perfectly!
Dan