Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

date - MySQL: How to select records for this week?

I have table temp with structure on sqlfiddle:

id(int 11 primary key)
name(varchar 100)
name2(varchar 100)
date(datetime)

I would like get record on this week, example if now 21.11.2013 i would like all rows on 18.11.2013 to 24.11.2013(on week)

Now I see next algorithm:

  1. obtain weekday
  2. calculate how many days ago was Monday
  3. calculate the date Monday
  4. calculate future date Sunday
  5. make a request on date

Tell me please, is exist a shorter algorithm (preferably in the query MySQL)?

ADD Question is: Why this query select record on date 17.11.2013(Sunday) - 23.11.2013(Saturday) and how get records on date 18.11.2013(Monday) - 24.11.2013(Sunday) ?

query:

select * from temp
where yearweek(`date`) = yearweek(curdate())

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use YEARWEEK():

SELECT *
FROM   your_table
WHERE  YEARWEEK(`date`, 1) = YEARWEEK(CURDATE(), 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...