我对我的mysql查询有疑问。 我想计算每天的记录数。 这有效,但我也希望看到计数为0的日期。 total为0的日期不在结果集中。 我怎么做? 这是我目前的查询:
SELECT COUNT(id) AS total_per_day,
DATE_FORMAT(reg_date, "%Y-%m-%d") as my_date
FROM my_table GROUP BY my_date
提前感谢您的回复。
答案 0 :(得分:0)
尝试自我加入:
SELECT COUNT(t.id) AS total_per_day, DATE_FORMAT(t.reg_date, "%Y-%m-%d") as my_date
FROM my_table t left outher join my_table t2 on t.id=t2.id GROUP BY t.my_date
答案 1 :(得分:0)
尝试此查询 -
-- Create this temp. table firstly!
-- CREATE TABLE days(d int);
-- INSERT INTO days(d) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
SELECT t.day, COUNT(mt.id) total_per_day FROM (
SELECT
min_date + INTERVAL t1.d + t2.d * 10 DAY day,
min_date,
max_date
FROM days t1, days t2,
(SELECT MIN(DATE(reg_date)) min_date, MAX(DATE(reg_date)) max_date FROM my_table) t3
HAVING day BETWEEN min_date AND max_date) t
LEFT JOIN my_table mt
ON t.day = DATE(mt.reg_date)
GROUP BY t.day