2012-02-03 34 views
1

我有一个包含日期和瞳孔ID的约会表,我试图每周自动复制一次。我想运行检测,如果每次约会都有其自身的副本提前一周的查询,所以原始数据是:在MySQL中有条件地复制记录

PupilID Date 
1   10th May 
2   16th May 

查询之后,

PupilID Date 
1   10th May 
2   16th May 
1   17th May 
2   23rd May 

我尝试使用以下没有运气。建议将不胜感激。我已经有代码完成这项工作,但它变得非常慢。

INSERT timetable (pupil_id,date) SELECT timetable.pupil_id AS pupil_id2,DATE_ADD(timetable.date,INTERVAL 14 DAY) AS date2 FROM timetable WHERE NOT EXISTS pupil_id2=timetable.pupil_id AND date2=timetable.date; 

回答

1

检查是否有未来的预约是否足够?

这给一个镜头:

insert into timetable (pupil_id,date) 
select t.pupil_id, DATE_ADD(t.date, INTERVAL 14 DAY) 
from timetable t 
where not exists (select 1 from timetable 
         where pupil_id = t.pupil_id 
         and date > t.date) 

你可以改变的最后一个子句来专门检查提前14天:

where not exists (select 1 from timetable 
         where pupil_id = t.pupil_id 
         and date = DATE_ADD(t.date, INTERVAL 14 DAY))   

我建议第一次查询,但。

+0

你让这看起来很简单!我需要添加一些其他条件,但该格式使其变得简单。 – 2012-02-03 17:09:33