背景:在一项行为实验中,大黄蜂被标记了一个唯一标识符以跟踪它们的运动。问题是标签只有 2 位数字,而群体可以多达 500 个人。这使得生成主键变得具有挑战性。
表格
(1)。每个选择都记录在此表中:
CREATE TABLE `exp8` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`bee_id` varchar(255) DEFAULT NULL,
`date_time` datetime DEFAULT NULL,
`choice` varchar(255) DEFAULT NULL,
`hover_duration` int(11) DEFAULT NULL,
`antennate_duration` int(11) DEFAULT NULL,
`land_duration` int(11) DEFAULT NULL,
`landing_position` varchar(255) DEFAULT NULL,
`remarks` longtext,
`validity` int(11) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=264;
LOCK TABLES `exp8` WRITE;
/*!40000 ALTER TABLE `exp8` DISABLE KEYS */;
INSERT INTO `exp8` (`id`, `bee_id`, `date_time`, `choice`, `hover_duration`, `antennate_duration`, `land_duration`, `landing_position`, `remarks`, `validity`)
VALUES
(1,NULL,'2013-05-14 15:38:31','right',1,0,0,NULL,NULL,1),
(2,NULL,'2013-05-18 10:27:15','left',1,0,0,NULL,NULL,1),
(3,'G5','2013-05-18 11:44:44','left',0,0,4,'yellow',NULL,1),
(4,'G5','2013-06-01 10:00:00','left',0,0,4,'yellow',NULL,1);
(2)。标签的开始和结束日期记录在下表中:
CREATE TABLE `tags` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`bee_id` varchar(255) DEFAULT NULL,
`tag_date` date DEFAULT NULL,
`colony_id` int(11) DEFAULT NULL,
`events` varchar(255) DEFAULT NULL,
`worker_age` varchar(255) DEFAULT NULL,
`tagged_by` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=406;
LOCK TABLES `tags` WRITE;
/*!40000 ALTER TABLE `tags` DISABLE KEYS */;
INSERT INTO `tags` (`id`, `bee_id`, `tag_date`, `colony_id`, `events`, `worker_age`, `tagged_by`)
VALUES
(1,'G5','2013-05-08',1,'birth','Adult','ET'),
(2,'G5','2013-05-20',NULL,'death','Adult','ET'),
(3,'G5','2013-05-29',1,'birth','Adult','ET');
(3)。区分标签的多种用途的查询:
select t.bee_id,
(case when t.death_date is null then 'Alive' else 'Dead' end) as status,
t.tag_date,
t.death_date,
(case when t.death_date is not null then timediff(t.death_date,t.tag_date)
else timediff(NOW(),t.tag_date) end) as age
from (select t.*,
(select t2.tag_date
from tags t2
where t2.bee_id = t.bee_id and
t2.events = 'death' and
t2.tag_date >= t.tag_date
limit 1
) as death_date
from tags t
where t.events = 'birth'
) t
group by t.bee_id, t.tag_date;
您对根据这些数据生成主键有什么建议吗?
提前致谢!列维