mysql日期范围之间的日期细分

时间:2013-12-10 04:35:08

标签: mysql date date-range

我有像这样的mySQL记录

name    sdate       edate  
John    2013-12-01  2013-12-04
Will    2013-12-04  2013-12-06
Smith   2013-12-02  2013-12-05

我需要对此结果进行单一查询

name    stay_date
John    2013-12-01
John    2013-12-02
John    2013-12-03
John    2013-12-04
Will    2013-12-04
Will    2013-12-05
Will    2013-12-06
Smith   2013-12-02
Smith   2013-12-03
Smith   2013-12-04
Smith   2013-12-05

Thanx很多提前..

1 个答案:

答案 0 :(得分:0)

为此,您需要一个计数(数字)表,您可以按以下方式创建和填充

CREATE TABLE tally(n INT NOT NULL PRIMARY KEY);
INSERT INTO tally(n)
SELECT a.N + b.N * 10 + 1 n
 FROM 
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
ORDER BY n;

现在您的查询可能看起来像

SELECT name, sdate + INTERVAL n.n - 1 DAY stay_date
  FROM table1 t JOIN tally n
    ON n.n <= edate - sdate + 1

输出:

+-------+------------+
| name  | stay_date  |
+-------+------------+
| John  | 2013-12-01 |
| John  | 2013-12-02 |
| John  | 2013-12-03 |
| John  | 2013-12-04 |
| Will  | 2013-12-04 |
| Will  | 2013-12-05 |
| Will  | 2013-12-06 |
| Smith | 2013-12-02 |
| Smith | 2013-12-03 |
| Smith | 2013-12-04 |
| Smith | 2013-12-05 |
+-------+------------+

这是 SQLFiddle 演示