简体   繁体   中英

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!

Use YEARWEEK() :

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

Use YEARWEEK . If you use WEEKOFYEAR you will get records of previous years also.

SELECT id, name, date
FROM table
WHERE YEARWEEK(date)=YEARWEEK(NOW());

For selecting records of day, week and month use this way:

function my_func($time, $your_date) {
if ($time == 'today') {
    $timeSQL = ' Date($your_date)= CURDATE()';
}
if ($time == 'week') {
    $timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($time == 'month') {
    $timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}

$Sql = "SELECT * FROM  your_table WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}

You can do it by following method

SELECT DATE_FORMAT("2017-06-15", "%U");

Get number of week (From 00 to 53 ) Where (Sunday 1st day and Monday last day of week)

May be useful for you.

example:

SELECT DISTINCT DATE_FORMAT('dates', '%U') AS weekdays FROM table_name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM