search
HomeDatabaseMysql TutorialHow to Generate a List of Dates Between Two Dates in MySQL?

How to Generate a List of Dates Between Two Dates in MySQL?

Generate a list of dates between two dates

To get a list of dates between two given dates, consider using a stored procedure like make_intervals to create a temporary table time_intervals filled with the required intervals. You can then join the data table with the time_intervals table to get the desired output.

make_intervals Stored Procedure (MySQL)

CREATE PROCEDURE make_intervals(
  startdate timestamp,
  enddate timestamp,
  intval integer,
  unitval varchar(10)
)
BEGIN
  -- 初始化局部变量
  declare thisDate timestamp;
  declare nextDate timestamp;
  set thisDate = startdate;

  -- 删除并创建用于区间的临时表
  drop temporary table if exists time_intervals;
  create temporary table if not exists time_intervals(
    interval_start timestamp,
    interval_end timestamp
  );

  -- 循环以递增并将区间插入到临时表中
  repeat
    -- 根据单位和区间计算下一个区间日期
    select
      case unitval
        when 'MICROSECOND' then timestampadd(MICROSECOND, intval, thisDate)
        when 'SECOND' then timestampadd(SECOND, intval, thisDate)
        when 'MINUTE' then timestampadd(MINUTE, intval, thisDate)
        when 'HOUR' then timestampadd(HOUR, intval, thisDate)
        when 'DAY' then timestampadd(DAY, intval, thisDate)
        when 'WEEK' then timestampadd(WEEK, intval, thisDate)
        when 'MONTH' then timestampadd(MONTH, intval, thisDate)
        when 'QUARTER' then timestampadd(QUARTER, intval, thisDate)
        when 'YEAR' then timestampadd(YEAR, intval, thisDate)
      end into nextDate;

    -- 将当前区间插入到临时表中
    insert into time_intervals select thisDate, timestampadd(MICROSECOND, -1, nextDate);
    set thisDate = nextDate;

  -- 继续直到当前日期达到或超过结束日期
  until thisDate >= enddate
  end repeat;
END;

Usage examples

For example, to create a list of dates between January 1, 2009 and January 13, 2009, you would call the make_intervals stored procedure as follows:

call make_intervals('2009-01-01 00:00:00', '2009-01-13 00:00:00', 1, 'DAY');

This will populate the time_intervals table with intervals representing each day in the specified date range. You can then join the data table with the time_intervals table to summarize the data based on these intervals.

The above is the detailed content of How to Generate a List of Dates Between Two Dates in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How does MySQL handle concurrency compared to other RDBMS?How does MySQL handle concurrency compared to other RDBMS?Apr 29, 2025 am 12:44 AM

MySQLhandlesconcurrencyusingamixofrow-levelandtable-levellocking,primarilythroughInnoDB'srow-levellocking.ComparedtootherRDBMS,MySQL'sapproachisefficientformanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancedfeatureslikePostgreSQL'sSerializa

How does MySQL handle transactions compared to other relational databases?How does MySQL handle transactions compared to other relational databases?Apr 29, 2025 am 12:37 AM

MySQLhandlestransactionseffectivelyusingtheInnoDBengine,supportingACIDpropertiessimilartoPostgreSQLandOracle.1)MySQLusesREPEATABLEREADasthedefaultisolationlevel,whichcanbeadjustedtoREADCOMMITTEDforhigh-trafficscenarios.2)Itoptimizesperformancewithabu

What are the data types available in MySQL?What are the data types available in MySQL?Apr 29, 2025 am 12:28 AM

MySQL data types are divided into numerical, date and time, string, binary and spatial types. Selecting the correct type can optimize database performance and data storage.

What are some best practices for writing efficient SQL queries in MySQL?What are some best practices for writing efficient SQL queries in MySQL?Apr 29, 2025 am 12:24 AM

Best practices include: 1) Understanding the data structure and MySQL processing methods, 2) Appropriate indexing, 3) Avoid SELECT*, 4) Using appropriate JOIN types, 5) Use subqueries with caution, 6) Analyzing queries with EXPLAIN, 7) Consider the impact of queries on server resources, 8) Maintain the database regularly. These practices can make MySQL queries not only fast, but also maintainability, scalability and resource efficiency.

How does MySQL differ from PostgreSQL?How does MySQL differ from PostgreSQL?Apr 29, 2025 am 12:23 AM

MySQLisbetterforspeedandsimplicity,suitableforwebapplications;PostgreSQLexcelsincomplexdatascenarioswithrobustfeatures.MySQLisidealforquickprojectsandread-heavytasks,whilePostgreSQLispreferredforapplicationsrequiringstrictdataintegrityandadvancedSQLf

How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools