如何显示start_date
和end_date
之间的日期列表?
我尝试使用group by DAY(start_date),DAY(end_date)
分组,但没有成功。
例如,在预订表中,它看起来像这样:
+----+-----------+--------+---------------------+---------------------+----------+
| id | client_id | car_id | start_date | end_date | status |
+----+-----------+--------+---------------------+---------------------+----------+
| 1 | 1 | 2 | 2015-10-03 00:00:00 | 2015-10-05 00:00:00 | Reserved |
| 2 | 3 | 5 | 2015-10-15 00:00:00 | 2015-10-17 00:00:00 | Hired |
+----+-----------+--------+---------------------+---------------------+----------+
我希望结果如下:
client_id car_id booked_date status
1 2 2015-10-03 Reserved
1 2 2015-10-04 Reserved
1 2 2015-10-05 Reserved
3 5 2015-10-15 Hired
3 5 2015-10-16 Hired
3 5 2015-10-17 Hired
答案 0 :(得分:1)
创建表callender:
CREATE TABLE IF NOT EXISTS `callender` (
`date` date NOT NULL,
PRIMARY KEY (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
插入日期:
INSERT INTO `callender` (`date`) VALUES
('2015-10-03'),
('2015-10-04'),
('2015-10-05'),
('2015-10-06'),
('2015-10-07'),
('2015-10-08'),
('2015-10-09'),
('2015-10-10'),
('2015-10-11'),
('2015-10-12'),
('2015-10-13'),
('2015-10-14'),
('2015-10-15'),
('2015-10-16'),
('2015-10-17'),
('2015-10-18');
运行查询:
SELECT client_id, car_id, date, status
FROM booking
LEFT JOIN callender ON (date >= start_date
AND date<=end_date)
答案 1 :(得分:0)
使用BETWEEN
- 关键字。
SELECT client_id, car_id, booked_date, status
FROM Your_table
WHERE booked_date BETWEEN start_date AND end_date
答案 2 :(得分:0)
或没有callender表:
SELECT client_id, car_id, date, status
FROM booking
LEFT JOIN
(SELECT curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Date
FROM
(SELECT 0 AS a
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) AS a
CROSS JOIN
(SELECT 0 AS a
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) AS b
CROSS JOIN
(SELECT 0 AS a
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) AS c ) AS callender ON (date >= start_date
AND date<=end_date