纯SQL获取当月全部日期(不借助任何表)

以前有个需求须要获取当月的全部需求,搜了一下实现SQL,不少都是借助其余表实现的:sql

https://blog.csdn.net/zhaofanjack/article/details/80231597优化

而后我想不用借助任何表实现这个功能,就想出以下杰做:.net

SELECT DATE(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY)) as monthOfDate FROM (
	SELECT 1 as monthOfday UNION ALL
	SELECT 2 as monthOfday UNION ALL
	SELECT 3 as monthOfday UNION ALL
	SELECT 4 as monthOfday UNION ALL
	SELECT 5 as monthOfday UNION ALL
	SELECT 6 as monthOfday UNION ALL
	SELECT 7 as monthOfday UNION ALL
	SELECT 8 as monthOfday UNION ALL
	SELECT 9 as monthOfday UNION ALL
	SELECT 10 as monthOfday UNION ALL
	SELECT 11 as monthOfday UNION ALL
	SELECT 12 as monthOfday UNION ALL
	SELECT 13 as monthOfday UNION ALL
	SELECT 14 as monthOfday UNION ALL
	SELECT 15 as monthOfday UNION ALL
	SELECT 16 as monthOfday UNION ALL
	SELECT 17 as monthOfday UNION ALL
	SELECT 18 as monthOfday UNION ALL
	SELECT 19 as monthOfday UNION ALL
	SELECT 20 as monthOfday UNION ALL
	SELECT 21 as monthOfday UNION ALL
	SELECT 22 as monthOfday UNION ALL
	SELECT 23 as monthOfday UNION ALL
	SELECT 24 as monthOfday UNION ALL
	SELECT 25 as monthOfday UNION ALL
	SELECT 26 as monthOfday UNION ALL
	SELECT 27 as monthOfday UNION ALL
	SELECT 28 as monthOfday UNION ALL
	SELECT 29 as monthOfday UNION ALL
	SELECT 30 as monthOfday UNION ALL
	SELECT 31 as monthOfday
)tb
WHERE MONTH(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY)) = MONTH(NOW())

这段SQL看起来是有点蠢,但很实用~~~摊手~~~code

原理就是取一个月中最多的天数(31天),经过UNION ALL 组成一个临时表,而后经过月中日期号减去当前日期计算日期(DATE(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY))),而后过滤当月的防止溢出(MONTH(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY)) = MONTH(NOW()))blog

还能实现其余功能,例如当月剩余日期get

SELECT DATE(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY)) as monthOfDate FROM (
	SELECT 1 as monthOfday UNION ALL
	SELECT 2 as monthOfday UNION ALL
    ...
	SELECT 31 as monthOfday
)tb
WHERE DAY(DATE_ADD(NOW(), INTERVAL tb.monthOfday - DAY(NOW()) DAY)) >= DAY(NOW())

用途还能很普遍,例如当月剩余天数、将来N天的日期什么的都不在话下~~SQL我就不写了class

如果哪位大牛有更好的实现或者优化还请多多指点......小弟在此谢过!!!原理

相关文章
相关标签/搜索