mysql count如果不为null,则返回0

new9mtju  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(427)

我需要清点日期之间的所有文章。我曾经 IFNULL(COUNT(*), 0) 返回null。

SELECT posts_count, dates.fulldate
FROM dates
LEFT JOIN 
   (SELECT IFNULL(COUNT(post_id), 0) AS posts_count, DATE_FORMAT(post_created_at, "%Y-%m-%d") AS pdate
   FROM posts
   WHERE DATE_FORMAT(post_created_at, "%Y-%m-%d") BETWEEN NOW() - INTERVAL 31 DAY AND NOW()
   GROUP BY DATE_FORMAT(post_created_at, "%Y-%m-%d")) t
ON t.pdate = dates.fulldate
WHERE dates.fulldate BETWEEN CURDATE() - INTERVAL 31 DAY AND CURDATE() ORDER BY dates.fulldate ASC;

结果是:

NULL |  2020-05-20    
NULL |  2020-05-21    
NULL |  2020-05-22    
7634 |  2020-05-23    
51224 | 2020-05-24

我想要的结果是:

0 |  2020-06-16   
1233 |  2020-06-15    
4354 |  2020-06-14   
   0 |  2020-06-13    
   0 |  2020-06-12
sauutmhj

sauutmhj1#

你的问题似乎比需要的复杂。我不认为分组按日期发布的子查询和按日期过滤两次的子查询有什么意义。
我认为你想要的逻辑是:

select count(p.post_id) post_count, d.fulldate
from dates d
left join posts p
    on  p.post_created_at >= d.fulldate
    and p.post_created_at <  d.fulldate + interval 1 day
where d.fulldate >= current_date - interval 1 month
group by d.fulldate
order by d.fulldate

我希望这应该比您原来的代码效率更高,特别是因为在post-date列上应用了not-date函数。我推荐一个关于 posts(post_created_at) 以充分利用此代码。

dxxyhpgq

dxxyhpgq2#

你需要做 IFNULL() 在主查询中,而不是在子查询中。子查询没有为缺少的日期返回任何行,因此甚至没有要转换为0的空计数。

SELECT IFNULL(posts_count, 0) AS posts_count, dates.fulldate
FROM dates
LEFT JOIN 
   (SELECT COUNT(*) AS posts_count, DATE_FORMAT(post_created_at, "%Y-%m-%d") AS pdate
   FROM posts
   WHERE DATE_FORMAT(post_created_at, "%Y-%m-%d") BETWEEN NOW() - INTERVAL 31 DAY AND NOW()
   GROUP BY DATE_FORMAT(post_created_at, "%Y-%m-%d")) t
ON t.pdate = dates.fulldate
WHERE dates.fulldate BETWEEN CURDATE() - INTERVAL 31 DAY AND CURDATE() 
ORDER BY dates.fulldate ASC;

相关问题