简体   繁体   English

从一个MySQL表中选择,即使count为0,也返回count(id)

[英]Selecting from one MySQL table, return count(id) even if count is 0

I've been scouring google for the answer to this, and I'm SURE it's easier than I'm making it, and I'd like to learn the right way to do this. 我一直在寻找google的答案,我敢肯定它比我做起来容易,而且我想学习正确的方法。

I have one table emails_sent that I'm selecting counts from and grouping by a column. 我有一个表emails_sent ,我从中选择计数并按列分组。 Each row has one of 3 type - "confirm", "1day", and "sameday". 每行具有3 type -“确认”,“ 1天”和“同一天”。 I'm also doing this by a certain date. 我也在某个日期之前这样做。 So let's say, here's an example query I'm selecting for today: 这么说吧,这是我今天要选择的示例查询:

SELECT Count(id) AS count, 
       type 
FROM   emails_sent 
WHERE  Date_format(date, '%Y-%m-%d') = '2013-03-29' 
GROUP  BY type 
ORDER  BY type; 

This is what it returns: 这是返回的内容:

+-------+---------+
| count | type    |
+-------+---------+
|    32 | confirm |
|     4 | 1day    |
+-------+---------+

Which is great, but there is also a third "type" that happens to have 0 records for today, but I need it to pull that count even if it's 0. 太好了,但还有第三个“类型”今天碰巧有0条记录,但是即使它是0,我也需要它来拉动该计数。

I've also tried creating a 2nd table with just those 3 "types" in it, and using a right join, but it still won't pull the 0 count. 我也尝试过创建仅包含这3个“类型”的第二张表,并使用右连接,但是它仍然不会拉0计数。 This is what I did with the two tables: 这是我对两个表所做的操作:

SELECT t.type, 
       Count(s.id) AS count 
FROM   emails_sent s 
       RIGHT JOIN email_types t 
               ON s.type = t.type 
WHERE  Date_format(s.date, '%Y-%m-%d') = '2013-03-29' 
GROUP  BY t.type; 

I'm sure it's just something simple that I'm missing. 我确定这只是我所缺少的简单东西。

Try this 尝试这个

SELECT t.type, 
       COALESCE( Count(s.id), 0 ) AS count 
FROM   email_types t 
       LEFT JOIN email_sent s 
               ON s.type = t.type 
WHERE  Date_format(s.date, '%Y-%m-%d') = '2013-03-29' 
GROUP  BY t.type; 

Note: I have used a LEFT JOIN instead, as 1 type has many emails 注意:我改用了LEFT JOIN ,因为1 type has many emails

如果我正确理解了该问题,您是否不能仅假设如果没有获得某种类型的记录,那是因为条目为0?

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

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