从历史表中导出数据

时间:2013-09-24 11:22:15

标签: mysql date

我有一个管理狗玩具库的数据库。

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

1 个答案:

答案 0 :(得分:0)

这一定对你有用。我使用您提供的数据在我的本地mysql数据库中进行了测试,并且运行良好。

select dth.toy_id, dth.created_date as start_date, 
       ifnull((select min(dth2.created_date) from dog_toy_history dth2 where dth2.created_date > dth.created_date and dth2.dog_id='2'),'2013-09-01') as end_date 
       from dog_toy_history dth
       where (dth.created_date between '2013-07-01' and '2013-09-01') and dog_id='2' ORDER by start_date;

我将为那些不熟悉mysql的人提供一些解释:

  • 内部选择会带来下一个玩具的 created_date 字段(如果存在)。这将代表当前玩具的 end_date

  • ifnull(exp1,exp2)指定下一个玩具不存在时的默认值。在这种情况下, end_date 将是输入的结束日期。