简体   繁体   English

当使用COUNT和GROUP BY时,MySQL包含零行

[英]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. 我正在尝试执行一个查询,该查询通过名为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. 我想要的结果是type_id和每种类型剩余的未售出产品数量。 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 . 您必须使用LEFT JOIN而不是INNER JOIN You start by selecting all voucher_types and then left join to find the count. 首先选择所有voucher_types ,然后进行左连接以查找计数。

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. 因为您正在执行INNER JOIN,所以您会自动排除没有相应凭证的类型。 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. 而且,据我所记得,COUNT总是会给您一个整数,因此不需要COALESCE。

Good luck, Alin 祝你好运,阿琳

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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