Retrieving data from MYSQL based on week number

后端 未结 3 867
迷失自我
迷失自我 2021-01-27 12:59

I am having a table as follows in MYSQL:

proj_id|hoursWorked|Date.  

The date field is of type Date; I want to retrieve all the e

相关标签:
3条回答
  • 2021-01-27 13:03

    Do not use something like WHERE WEEK(column)=something - this is a performance killer: It will calculate the week number on all rows, even if they don't match. In addition to that it will make it impossible to use an index ont this column.

    Instead calculate an absolute begin and end date or point in time, depending on your data type, then use BETWEEN. This will do no calculations on non-matching rows and allow the use of an index.

    Rule of thumb: If you have the choice between a calculation on a constant and on a field, use the former.

    0 讨论(0)
  • 2021-01-27 13:22

    use MySQL WEEK() function.

    SELECT WEEK(dateColumn)
    FROM...
    WHERE WEEK(dateColumn) = 1
    
    • WEEK()

    from MySQL Docs

    This function returns the week number for date. The two-argument form of WEEK() enables you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53.

    0 讨论(0)
  • 2021-01-27 13:29

    Use WEEK

    select * from your_table
    where week(`Date`) = week('2012-12-01')
    

    If you want to get only records from the current week you can do

    select * from your_table
    where week(`Date`) = week(curdate())
    
    0 讨论(0)
提交回复
热议问题