我有一张约会表,其中包含我想要每周自动复制的日期和学生ID。我想运行一个查询,该查询检测每个约会是否提前一周都有自己的副本,因此原始数据为:
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;
答案 0 :(得分: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))
我推荐第一个查询。