简体   繁体   中英

MySQL include zero rows when using COUNT with GROUP BY

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM