我有一个管理狗玩具库的数据库。
该dog_toy_history
表记录了狗从玩具图书馆借出的玩具。退回玩具后,狗只能拥有新玩具,狗一次只能拥有一个玩具。
CREATE TABLE `dog_toy_history` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dog_id` int(10) unsigned NOT NULL,
`toy_id` varchar(8) NOT NULL,
`created_date` datetime NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `dog_toy_history`
(`id`,`dog_id`,`toy_id`,`created_date`)
VALUES
(1,1,'a','2013-07-05 00:00:00'),
(2,2,'b','2013-07-15 00:00:00'),
(3,3,'c','2013-07-20 00:00:00'),
(4,1,'d','2013-07-25 00:00:00'),
(5,2,'a','2013-08-05 00:00:00'),
(6,1,'b','2013-08-10 00:00:00'),
(7,2,'d','2013-08-15 00:00:00'),
(8,1,'a','2013-08-20 00:00:00');
给定一个 dog_id 和一个日期范围,我希望能够确定狗在该范围内拥有的玩具,以及它们从和到的日期。
示例查询 1
set @dog_id = 1;
set @start_date = '2013-07-05';
set @end_date = '2013-07-25';
<run special query> ... desired result:
toy_id, start_date, end_date
a 2013-07-05 2013-07-25
d 2013-07-25 2013-07-25
示例查询 2
set @dog_id = 1;
set @start_date = '2013-07-05';
set @end_date = '2013-08-19';
<run special query> ... desired result:
toy_id, start_date, end_date
a 2013-07-05 2013-07-25
d 2013-07-25 2013-08-10
b 2013-08-10 2013-08-19
示例查询 2
set @dog_id = 2;
set @start_date = '2013-07-01';
set @end_date = '2013-09-01';
<run special query> ... desired result:
toy_id, start_date, end_date
b 2013-07-15 2013-08-05
a 2013-08-05 2013-08-15
d 2013-08-15 2013-09-01