mysql 以 0 计
mysql count with 0
我有 2 个 table,一个 table 个月和一个 table 广告。我想 return 每个月来自广告的所有不同电子邮件。
Table 广告:created_at 是 DATETIME。
Table 个月:id_month(INT 和主键)
我尝试使用左连接 :
SELECT Months.id_month,count(distinct Ad.email)
FROM `Months` left outer join `Ad`
ON id_month = MONTH(Ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
但是没有 12 月的结果,也没有 return 0。(只有 1 到 11 月份的结果)
有什么想法吗?
我发现如果我加上这个条件:
WHERE YEAR(Ad.created_at)=2015
然后它不会 return 12 月的 0.. 为什么?
SELECT Months.id_month,count(distinct Ad.email)
FROM `Months` left join `Ad`
ON id_month = MONTH(Ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
试试这个
SELECT Months.id_month,count(Ad.email) Emails
FROM `Months`
JOIN `Ad` ON Months.id_month = MONTH(Ad.created_at)
GROUP BY Months.id_month
ORDER BY Months.id_month ASC
尝试使用 if 语句。我刚刚检查了 SQLFIDDLE 它工作正常。
SELECT months.id_month,
IF(Count(DISTINCT ad.email), Count(DISTINCT ad.email), 0)
FROM `months`
LEFT OUTER JOIN `ad`
ON id_month = Month(ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
基于 OP 对 @Dhaval Asodariya 回答
的评论
您应该将 Ad
上的过滤器移动到 LEFT join
条件的 ON
条件。
当您在 where
子句中保留右侧 table 过滤器时,Left outer join
将隐式转换为 INNER JOIN
。
SELECT months.id_month,
Count(DISTINCT ad.email)
FROM `months`
LEFT OUTER JOIN `ad`
ON id_month = Month(ad.created_at)
AND Year(ad.created_at) = 2015
GROUP BY id_month
ORDER BY id_month ASC
我有 2 个 table,一个 table 个月和一个 table 广告。我想 return 每个月来自广告的所有不同电子邮件。
Table 广告:created_at 是 DATETIME。
Table 个月:id_month(INT 和主键)
我尝试使用左连接 :
SELECT Months.id_month,count(distinct Ad.email)
FROM `Months` left outer join `Ad`
ON id_month = MONTH(Ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
但是没有 12 月的结果,也没有 return 0。(只有 1 到 11 月份的结果)
有什么想法吗?
我发现如果我加上这个条件:
WHERE YEAR(Ad.created_at)=2015
然后它不会 return 12 月的 0.. 为什么?
SELECT Months.id_month,count(distinct Ad.email)
FROM `Months` left join `Ad`
ON id_month = MONTH(Ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
试试这个
SELECT Months.id_month,count(Ad.email) Emails
FROM `Months`
JOIN `Ad` ON Months.id_month = MONTH(Ad.created_at)
GROUP BY Months.id_month
ORDER BY Months.id_month ASC
尝试使用 if 语句。我刚刚检查了 SQLFIDDLE 它工作正常。
SELECT months.id_month,
IF(Count(DISTINCT ad.email), Count(DISTINCT ad.email), 0)
FROM `months`
LEFT OUTER JOIN `ad`
ON id_month = Month(ad.created_at)
GROUP BY id_month
ORDER BY id_month ASC
基于 OP 对 @Dhaval Asodariya 回答
的评论您应该将 Ad
上的过滤器移动到 LEFT join
条件的 ON
条件。
当您在 where
子句中保留右侧 table 过滤器时,Left outer join
将隐式转换为 INNER JOIN
。
SELECT months.id_month,
Count(DISTINCT ad.email)
FROM `months`
LEFT OUTER JOIN `ad`
ON id_month = Month(ad.created_at)
AND Year(ad.created_at) = 2015
GROUP BY id_month
ORDER BY id_month ASC