the original data in table X
+----------+-----+
|Date |Count|
+----------+-----+
|2014-01-15|44 |
+----------+-----+
|2014-01-01|5 |
+----------+-----+
|2013-12-10|1 |
+----------+-----+
what I want to display is below :
+----------+-----+
|Date |Count|
+----------+-----+
|2014-01-15|44 |
+----------+-----+
|2014-01-14|0 |
+----------+-----+
|2014-01-13|0 |
+----------+-----+
|2014-01-12|0 |
+----------+-----+
|... |... |
*p/s and so on until 2013-12-14 or 2013-12-15
*how to solve the problem - 'curdate'/'NOW'/'subdate' is not a recognized built-in function name.
In MySQL, you have to do some thing like this:
select date_sub(date(now()), interval n.n day), coalesce(t.`count`, 0)
from (select 0 as n union all select 1 union all select 2 union all select 3 union all
. . .
select 30
) n left join
table t
on t.date = date_sub(date(now()), interval n.n day);
The first part is a manual list of 30 numbers.
One option is to create a date lookup table and then use an outer join
with date_sub
. This query should work for you:
select d.datefield, coalesce(x.count,0) count
from datelookup d
left join x on d.datefield = x.datefield
where d.datefield > date_sub(curdate(), interval 30 day)
and d.datefield <= curdate()
order by d.datefield desc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.