简体   繁体   中英

Retrieving data from MYSQL based on week number

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 entries from a table depending on a given week number for the project in my java based web application. Please help me to achieve this.

I am unable to write a single query that will allow me to do so.

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.

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())

use MySQL WEEK() function.

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

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.

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