在mysql中查找开始日期和结束日期之间的日期

时间:2013-09-28 07:19:16

标签: mysql date between

我有两列,一个是开始日期,另一个是结束日期。我需要在两个日期之间找到每一天。

需要在另一个包含两个coloums的表中,一个名称pno引用第一个表中的pno的id,另一个名称引用开始日期和结束日期之间的日期。< / p>

作为一个例子,这可能是我的输入

 
pno         startdate        end date
p1          2012-12-03      2012-12-06     
p2          2013-01-05      2013-01-08
p3          2013-01-15      2012-01-20

这必须是我的输出。

pno          dates
----------
p01          2012-12-03 
p01          2012-12-04 
p01          2012-12-05 
p01          2012-12-06
p02          2013-01-05
p02          2013-01-06
p02          2013-01-07
p02          2013-01-08
p03          2013-01-15
...

1 个答案:

答案 0 :(得分:4)

你可以这样做

SELECT pno, startdate + INTERVAL q.n - 1 DAY dates
  FROM table1 t CROSS JOIN
(
   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
) q 
 WHERE q.n - 1 <= DATEDIFF(enddate, startdate) 
 ORDER BY pno, dates

子查询生成一系列从1到100的数字。您可以根据需要调整它(如果日期差异跨越多于或少于100天),或者如果您执行了一个持久的计数(数字)表,则完全替换它很多这样的问题。

输出:

+------+------------+
| pno  | dates      |
+------+------------+
| p1   | 2012-12-03 |
| p1   | 2012-12-04 |
| p1   | 2012-12-05 |
| p1   | 2012-12-06 |
| p2   | 2013-01-05 |
| p2   | 2013-01-06 |
| p2   | 2013-01-07 |
| p2   | 2013-01-08 |
| p3   | 2013-01-15 |
| p3   | 2013-01-16 |
| p3   | 2013-01-17 |
| p3   | 2013-01-18 |
| p3   | 2013-01-19 |
| p3   | 2013-01-20 |
+------+------------+

这是 SQLFiddle 演示


更新:要创建并填充持久的计数表,请使用

CREATE TABLE tally (n INT NOT NULL PRIMARY KEY);

INSERT INTO tally (n)
SELECT a.n + b.n * 10 + c.n * 100 + d.n * 1000 + 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
,(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) c
,(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) d
ORDER BY n;

您将在计数表中包含从1到10000的数字序列。这样您就可以使用超过27年的日期范围。

现在查询归结为

SELECT pno, startdate + INTERVAL q.n - 1 DAY dates
  FROM table1 t CROSS JOIN tally q 
 WHERE q.n - 1 <= DATEDIFF(enddate, startdate) 
 ORDER BY pno, dates

这是 SQLFiddle 演示