Fetching count from database by days

时间:2015-10-06 08:52:01

标签: mysql

I have the following structure:

id | some_foreign_id | date
1    5                 2015-09-29 23:14:23
2    5                 2015-09-29 14:13:21
3    8                 2015-09-28 22:23:12

For the specified some_foreign_id I want to return the count of rows in this table for each day from last 2 weeks. I created this:

SELECT DATE(t.sent_at), COUNT(*)
FROM table t
INNER JOIN sometable st ON st.some_id = t.id
INNER JOIN someOtherTable sot ON sot.someother_id = st.id
WHERE t.sent_at >= DATE_ADD(CURDATE(), INTERVAL -14 DAY)
AND t.some_foreign_id = 5
GROUP BY DATE(t.sent_at);

It shows some results, but:

  1. Doesn't show 0's if the day has 0 records.
  2. Changing interval to -15 changes the count from the last day - don't know why.

How could I do this properly?

1 个答案:

答案 0 :(得分:0)

要解决1.,您需要将联接保留为this并使用IFNULL()

要解决2.(或尝试),请尝试将您的查询更改为此(我建议您先解决此问题):

SELECT DATE(t.sent_at), COUNT(*)
FROM table t
INNER JOIN sometable st ON st.some_id = t.id
INNER JOIN someOtherTable sot ON sot.someother_id = st.id
WHERE DATE(t.sent_at) >= DATE(DATE_ADD(CURDATE(), INTERVAL -14 DAY))
AND t.some_foreign_id = 5
GROUP BY DATE(t.sent_at);