共計 1693 個字符,預計需要花費 5 分鐘才能閱讀完成。
這篇文章主要介紹“mysql 如何查詢近一周的數據”,在日常操作中,相信很多人在 mysql 如何查詢近一周的數據問題上存在疑惑,丸趣 TV 小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”mysql 如何查詢近一周的數據”的疑惑有所幫助!接下來,請跟著丸趣 TV 小編一起來學習吧!
在 mysql 中,可以利用 select 語句查詢近一周的數據,語法為“select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) = date(column_time);”。
本教程操作環境:windows10 系統、mysql8.0.22 版本、Dell G3 電腦。
mysql 怎么查詢近一周的數據
語法如下:
select * from table where DATE_SUB(CURDATE(), INTERVAL 7 DAY) = date(column_time);
拓展知識:
查詢一天:
select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate();
查詢一個月:
select * from table where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) = date(column_time);
示例如下:
效果如圖(這里 SQL 語句中的一周范圍是指星期一到星期日,星期一為一周的第一天,因是 8 月 11 日查詢的,所以只顯示星期一到星期六的結果):
日歷:
簡單來說就是用今天的日期生成前七天的日期(利用 union all 命令),并根據星期一的日期條件刷選出本周的日期
SELECT DATE(subdate(curdate(),date_format(curdate(), %w )-1)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 1 day)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 2 day)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 3 day)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 4 day)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 5 day)) as thisweek
union all
SELECT DATE(DATE_ADD(subdate(curdate(),date_format(curdate(), %w )-1), interval 6 day)) as thisweek
解析:
SELECT DATE(subdate(curdate(),date_format(curdate(),’%w’)-1))
得到的是這周的第一天(星期一到星期天為一周);也即 8 月 6 日
到此,關于“mysql 如何查詢近一周的數據”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注丸趣 TV 網站,丸趣 TV 小編會繼續努力為大家帶來更多實用的文章!