How to use MySQL to query last week’s data
When processing time series data, it is often necessary to retrieve records based on a specific time period. This article will introduce how to query last week's data and start the week with Sunday.
Query structure:
We will use the following MySQL query structure:
<code class="language-sql">SELECT column_list FROM table_name WHERE date_column BETWEEN start_date AND end_date;</code>
Calculate start and end dates:
To determine the start and end dates of the previous week, we will use the DATE_SUB() and NOW() functions:
DATE_SUB(NOW(), INTERVAL 1 WEEK)
: Subtract one week from the current date and return the starting date of the previous week. NOW()
: Returns the current date and time. Example query:
Assuming the table structure and sample data are known, the following query will select the id column value from the last week:
<code class="language-sql">SELECT id FROM tbname WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 1 WEEK) AND NOW();</code>
Expected output:
Based on the provided table values, the expected output of the query is 5, 6, 8, which represents the id values recorded within the last week.
The above is the detailed content of How to Select Data from the Last Week in MySQL?. For more information, please follow other related articles on the PHP Chinese website!