我想知道是否有可能限制用户插入重复的注册记录。例如,一些团队是从5.1.2009到31.12.2009注册的。然后有人为5.2.2009 - 31.12.2009注册同一个团队。通常,end_date不是问题,但start_date不应介于现有记录的开始日期和结束日期之间
CREATE TABLE IF NOT EXISTS `ejl_team_registration` (
`id` int(11) NOT NULL auto_increment,
`team_id` int(11) NOT NULL,
`league_id` smallint(6) NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
PRIMARY KEY (`team_id`,`league_id`,`start_date`),
UNIQUE KEY `id` (`id`)
);发布于 2009-02-02 14:05:41
我会在程序的代码中检查它,而不是在数据库中。
发布于 2009-02-02 14:09:42
如果你想在数据库中做到这一点,你可以使用pre-insert trigger,如果有任何冲突的记录,它将失败。
发布于 2009-02-03 09:20:33
这是一个典型的时间重叠问题。假设您想要在A (start_date)到B (end_date)这段时间内注册某个团队。
在接下来的情况下,不应该允许这样做:
在这些情况下,注册会导致时间重叠。在任何其他地方它都不会,所以你可以自由注册。
在sql中,检查应为:
select count(*) from ejl_team_registration
where (team_id=123 and league_id=45)
and ((start_date>=A and end_date<=B)
or (start_date<=A and end_date>=A)
or (start_date<=B and end_date>=B)
);..。当然还有team_id、league_id、A和B的实值。
如果查询返回0以外的任何值,则该团队已经注册,再次注册将导致时间重叠。
为了演示这一点,让我们填充该表:
insert into ejl_team_registration (id, team_id, league_id, start_date, end_date)
values (1, 123, 45, '2007-01-01', '2007-12-31')
, (2, 123, 45, '2008-01-01', '2008-12-31')
, (3, 123, 45, '20010-01-01', '2010-12-31');让我们检查一下,我们是否可以在'2009-02-03‘和’2009-12-31‘之间在leage 45中注册team 123:
select count(*) from ejl_team_registration
where (team_id=123 and league_id=45)
and ((start_date<='2009-02-03' and end_date>='2009-12-31')
or (start_date<='2009-03-31' and end_date>='2009-03-02')
or (start_date<='2009-12-31' and end_date>='2009-12-31')
);结果是0,所以我们可以自由注册。在'2009-02-03‘和'2011-12-31’之间注册是不可能的。我将把检查其他值作为练习留给您。
PS:你提到的结束日期通常不是问题。事实上是这样的,因为插入具有无效结束日期的条目也会导致重叠。
https://stackoverflow.com/questions/503292
复制相似问题