Home > Database > Mysql Tutorial > How to Select Data from the Last Week in MySQL?

How to Select Data from the Last Week in MySQL?

Susan Sarandon
Release: 2025-01-08 16:42:42
Original
247 people have browsed it

How to Select Data from the Last Week in MySQL?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template