简体   繁体   中英

How to create multiple rows from single row with time interval in MySQL

I've a table with start_date, end_date and frequency. Using MySQL query I want to generate multiple rows with every date between start_date and end_date. Here are the tables:

ID | start_date |  end_date  | frequency
----------------------------------------
 1 | 1402876800 | 1403049600 | daily

Now I want the query output as following:

active_date | start_date |  end_date  | frequency
--------------------------------------------------
 1402876800 | 1402876800 | 1403049600 | daily
 1402963200 | 1402876800 | 1403049600 | daily
 1403049600 | 1402876800 | 1403049600 | daily

All dates are in timestamp value.

Thanks in advance.

The simplest way is to create a date table and join on it using a between condition, eg,

SELECT d.date AS active_date, t.start_date, t.end_date, t.frequency
FROM {your_table} AS t
INNER JOIN {date_lookup_table} AS d
ON d.date BETWEEN t.start_date AND t.end_date

You could also use a procedure to calculate this... But in my experience having a date lookup table is pretty helpful in general, especially if you do things like add month and year to it. And it's definitely a lot simpler to use and to troubleshoot. If it were me, I'd add a date lookup table, make sure it's got an index on date, and move on.

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