我当然可以用服务器端语言执行此操作,但我想知道是否可以在SQL中执行此操作。
我有一张表:
CREATE TABLE `dates` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`date_from` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`date_to` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
);
有一些数据,如
+----+---------------------+---------------------+
| id | date_from | date_to |
+----+---------------------+---------------------+
| 1 | 2013-02-27 00:00:00 | 2013-03-01 00:00:00 |
| 2 | 2013-02-18 00:00:00 | 2013-02-20 00:00:00 |
+----+---------------------+---------------------+
(所有日期都是午夜)
我想选择这些以某种方式回来:
2013-02-27 00:00:00
2013-02-28 00:00:00
2013-03-01 00:00:00
2013-02-18 00:00:00
2013-02-19 00:00:00
2013-02-20 00:00:00
即指定范围内的所有日期。
有什么想法吗?
答案 0 :(得分:1)
您可以尝试使用此单个查询(它应该完成此任务):
SELECT * FROM (
SELECT dates.date_from + INTERVAL a + b DAY dte
FROM
(SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3
UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7
UNION SELECT 8 UNION SELECT 9 ) d,
(SELECT 0 b UNION SELECT 10 UNION SELECT 20
UNION SELECT 30 UNION SELECT 40) m, dates
WHERE dates.date_from + INTERVAL a + b DAY <= dates.date_to
ORDER BY a + b ) e ORDER BY dte;
查看SQL Fiddle。