Home > Database > Mysql Tutorial > How to Generate a Date Range in MySQL Using a SELECT Query?

How to Generate a Date Range in MySQL Using a SELECT Query?

Susan Sarandon
Release: 2025-01-19 01:26:08
Original
582 people have browsed it

How to Generate a Date Range in MySQL Using a SELECT Query?

Use MySQL SELECT query to generate date range

Many applications need to get a series of dates within a specified date range. The MySQL SELECT query accomplishes this.

Query construction

To generate a list of dates between two given dates, you can use the following query:

<code class="language-sql">SELECT * FROM
(SELECT ADDDATE('1970-01-01', t4.i * 10000 + t3.i * 1000 + t2.i * 100 + t1.i * 10 + t0.i) AS selected_date FROM
 (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0,
 (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t1,
 (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t2,
 (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t3,
 (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t4) v
WHERE selected_date BETWEEN '2012-02-10' AND '2012-02-15';</code>
Copy after login

This query generates a date range from '2012-02-10' to '2012-02-15', with each date displayed as a single row in the result set.

Description

A nested SELECT statement in the main query is used to construct a list of dates. Each SELECT statement generates a sequence of one-digit numbers from 0 to 9. These sequences are then combined using the " " operator to form a complete date string. The "ADDDATE" function is used to add these numbers to '1970-01-01' to generate the desired date range.

The above is the detailed content of How to Generate a Date Range in MySQL Using a SELECT Query?. 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