在MySQL中,如果需要查詢某個月份的最后一天日期,可以使用以下兩種方法:
-- 方法一:使用LAST_DAY()函數取月底最后一天 SELECT LAST_DAY('2022-05-01'); -- 結果為2022-05-31 -- 方法二:使用DATE_SUB()函數減去一天來取月底最后一天 SELECT DATE_SUB(DATE_ADD('2022-05-01',INTERVAL 1 MONTH), INTERVAL 1 DAY); -- 結果為2022-05-31
其中,方法一使用MySQL自帶的LAST_DAY()函數來獲取某個日期所在月份的最后一天的日期。
方法二則是通過先使用DATE_ADD()函數來將日期加上一個月,然后再使用DATE_SUB()函數減去一天來獲取該月份的最后一天。
當需要查詢一段時間內,每個月份的最后一天時,可以將以上兩種方法結合使用來實現:
-- 查詢2022年1月至12月份最后一天 SELECT MONTH(date) AS month, -- 返回月份 LAST_DAY(date) AS last_day FROM (SELECT ADDDATE('2022-01-01', INTERVAL (a1 + a10 * 10 + a100 * 100 + a1000 * 1000) MONTH) AS date FROM (SELECT 0 AS a1 UNION ALL SELECT 1 AS a1 UNION ALL SELECT 2 AS a1 UNION ALL SELECT 3 AS a1 UNION ALL SELECT 4 AS a1 UNION ALL SELECT 5 AS a1 UNION ALL SELECT 6 AS a1 UNION ALL SELECT 7 AS a1 UNION ALL SELECT 8 AS a1 UNION ALL SELECT 9 AS a1) AS tens, (SELECT 0 AS a10 UNION ALL SELECT 1 AS a10 UNION ALL SELECT 2 AS a10 UNION ALL SELECT 3 AS a10 UNION ALL SELECT 4 AS a10 UNION ALL SELECT 5 AS a10 UNION ALL SELECT 6 AS a10 UNION ALL SELECT 7 AS a10 UNION ALL SELECT 8 AS a10 UNION ALL SELECT 9 AS a10) AS hundreds, (SELECT 0 AS a100 UNION ALL SELECT 1 AS a100 UNION ALL SELECT 2 AS a100 UNION ALL SELECT 3 AS a100 UNION ALL SELECT 4 AS a100) AS thousands) AS months;
以上代碼可以查詢出2022年1月至12月份的最后一天,可以根據需求自行修改。