mysql常用时间列表的查询——七天内、本月、本周、某天
作者:互联网
最近七天的日期列表
SELECT @s :=@s + 1 as `index`, DATE(DATE_SUB(CURRENT_DATE, INTERVAL @s DAY)) AS `date`
FROM mysql.help_topic,(SELECT @s := -1) temp
WHERE @s < 6
ORDER BY 'date'
一天24小时查询(0 - 23)
- SELECT @d := @d + 1 `hour`
- FROM mysql.help_topic,(SELECT @d := -1) temp
- WHERE @d < 23
本周日期列表
SELECT @a :=@a + 1 as `index`, DATE(ADDDATE(CURRENT_DATE, INTERVAL @a DAY)) AS `date`
FROM mysql.help_topic,(SELECT @a := 0) temp
WHERE @a < 6 - WEEKDAY(CURRENT_DATE)
UNION
SELECT @s :=@s - 1 as `index`, DATE(DATE_SUB(CURRENT_DATE, INTERVAL @s DAY)) AS `date`
FROM mysql.help_topic,(SELECT @s := WEEKDAY(CURRENT_DATE) + 1) temp
WHERE @s > 0
ORDER BY `date`
本月日期列表
SELECT @a :=@a + 1 as `index`, DATE(ADDDATE(CURRENT_DATE, INTERVAL @a DAY)) AS `date`
FROM mysql.help_topic,(SELECT @a := 0) temp
WHERE @a < DAY(LAST_DAY(CURRENT_DATE)) - DAY(CURRENT_DATE)
UNION
SELECT @s :=@s - 1 as `index`, DATE(DATE_SUB(CURRENT_DATE, INTERVAL @s DAY)) AS `date`
FROM mysql.help_topic,(SELECT @s := day(CURRENT_DATE)) temp
WHERE @s > 0
ORDER BY `date`
有了上面几张临时表,解决时间段缺失的问题就简单了。只需要按需选取上述临时表作为主表,连接统计sql即可。
SELECT day_temp.date, COALESCE(stat_price.price, 0) AS price
FROM (
SELECT @a :=@a + 1 as `index`, DATE(ADDDATE(CURRENT_DATE, INTERVAL @a DAY)) AS `date`
FROM mysql.help_topic,(SELECT @a := 0) temp
WHERE @a < DAY(LAST_DAY(CURRENT_DATE)) - DAY(CURRENT_DATE)
UNION
SELECT @s :=@s - 1 as `index`, DATE(DATE_SUB(CURRENT_DATE, INTERVAL @s DAY)) AS `date`
FROM mysql.help_topic,(SELECT @s := day(CURRENT_DATE)) temp
WHERE @s > 0
ORDER BY `date`
) AS day_temp
LEFT JOIN
(
SELECT DATE(created_date) AS date, SUM(total_price) AS price
FROM t_order
WHERE MONTH(created_date) = MONTH(CURRENT_DATE)
AND YEAR(created_date) = YEAR(CURRENT_DATE)
GROUP BY DATE(created_date)
) AS stat_price
ON day_temp.date = stat_price.date
标签:七天,列表,CURRENT,date,mysql,DATE,DAY,SELECT 来源: https://www.cnblogs.com/aliRicky/p/14968251.html