我的日期字段(artists.onlineDate
)是yyy-mm-dd hh:mm:ss
现在我得到了:
-- Today
SELECT * FROM artists WHERE DATE(artists.onlineDate) = CURDATE()
-- Current Week
SELECT * FROM artists WHERE WEEK(artists.onlineDate, 3) = WEEK(CURDATE(), 3)
-- Current Month
SELECT * FROM artists WHERE MONTH(artists.onlineDate) = MONTH(CURDATE())
-- Current Year
SELECT * FROM artists WHERE YEAR(artists.onlineDate) = YEAR(CURDATE())
但我需要的是:昨天,上周,上个月,去年
我试着解释一下。如果我们星期三到达,我使用SELECT * FROM artists WHERE DATE(artists.onlineDate) = CURDATE()
,那么我星期一到星期三。
我希望星期一星期一到星期天。以前的日历周。
月和年也一样。
我感觉SUB_DATE
不正确。
有什么建议吗?
答案 0 :(得分:3)
好的,我找到了我想要的东西:
MySQL Query to select data from last week?
SELECT * FROM testwoche
WHERE WEEK (datum, 3) = WEEK(current_date, 3) - 1
AND YEAR(datum) = YEAR(current_date) ORDER BY datum DESC
月份相同
SELECT * FROM testwoche
WHERE month (datum) = month(current_date) - 1
AND YEAR(datum) = YEAR(current_date)
ORDER BY datum DESC
这回顾了从星期一到星期日和上个月的最后一周
感谢大家的帮助!
答案 1 :(得分:0)
我认为您可以使用SUBTIME功能:https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_subtime
我没有时间真正测试它,但我认为你明白这个想法:
昨天:
SELECT * FROM artists WHERE DATE(artists.onlineDate) = SUBTIME(CURDATE(),'1 0:0:0');
上周
SELECT * FROM artists WHERE WEEK(artists.onlineDate, 3) = WEEK(SUBTIME(CURDATE(),'7 0:0:0'), 3)
上个月
SELECT * FROM artists WHERE MONTH(artists.onlineDate) = MONTH(SUBTIME(CURDATE(),'31 0:0:0'))
去年
SELECT * FROM artists WHERE YEAR(artists.onlineDate) = YEAR(SUBTIME(CURDATE(),'365 0:0:0'))
答案 2 :(得分:0)
要获得特定的周/月/年(当您的数据库包含数年的数据且当前时间是新年的开始时仍然有效),这应该有效:
SELECT * FROM testwoche WHERE
((YEAR(CURDATE())-YEAR(datum)))*52-WEEK(datum,3)+WEEK(CURDATE(),3) = 1;
如果您想要两周前,可以将其更改为=2
(如果您想要当前周,从周一到当天:=0
)。如果您想要上个月,请将WEEK
功能更改为MONTH
。