純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

如果哪位大牛有更好的實現或者優化還請多多指點......小弟在此謝過!!!原理

相關文章
相關標籤/搜索