有人可以帮我写一个MySQL查询来更新一些我需要从损坏的源中重新创建的数据。由于编程错误,我不得不删除大约9000行损坏的数据。我有一份好数据的副本,但是无法计算出将这些好数据返回到已修复表中的联接。
我有一所学校的2张桌子,下面是相关列
Table A – tbl_Lessons
Lesson_id
Lesson_class_id
Lesson_date
Lesson_term
Table B – tbl_Register
Register_id
Register_lesson_id
Register_student_id
Register_status
Register_update_by
Register_update_dat
因此,对于每个class_id,每个授课日期都有一个唯一的lesson_id。
对于每个lesson_id,每个受教学生都有一个唯一的注册表项。
必须重新创建当前学期的所有课程,因此也必须重新创建所有课程的注册。
Table C – Backup Data before deletion.
(Create table tbl_tmp_register as
select * from tbl_register inner join tbl_lessons on lesson_id = register_lesson_id
where lesson_term = "autumn 2019")
Lesson_id
Lesson_class_id
Lesson_date
Lesson_term
Register_id
Register_lesson_id
Register_student_id
Register_status
Register_update_by
Register_update_date
所以我想做的是用备份表中的数据更新表B(register_status,register_update_by,register_update_date)。通过在备份表中查找与lesson_class_id,lesson_date和register_student_id匹配的行,我知道应该是什么,但是我无法编写SQL来获取复制的数据。我尝试过很多次,但失败了。我认为这很接近更新一个字段,但是即使我一天将注册范围缩小到一个类,也似乎只是挂了服务器。
update tbl_register as r inner join tbl_lessons as l on r.register_lesson_id = l.lesson_id,
(select register_student_status from tbl_tmp_register as TTR inner join tbl_lessons as L on L.lesson_class_id = TTR.lesson_class_id AND l.lesson_Date = TTR.Lesson_date) as tt
Set r.register_student_status = tt.register_student_status
where l.lesson_class_id = 000 and l.lesson_date = '2019-xx-yy';
如果我通过更直接的查询尝试另一种方式,我也会挂服务器。
update tbl_register as dest
inner join tbl_tmp_register as srce
on srce.register_student_id = dest.register_student_id
inner join tbl_lessons as otsrce
on otsrce.lesson_class_id = srce.lesson_class_id and otsrce.lesson_date = srce.lesson_date
set dest.register_student_status = srce.register_student_status
我知道我已经接近了,但还不能完全正确地加入联接。 任何帮助,不胜感激。
使用NBK的示例数据进行编辑: 在备份数据集中,register_id和lesson_id与register和Lesson表中的新数据集不同,因为它们已经重新生成,因此新旧之间的链接是学生ID,班级ID和班级日期。 / p>
Sample data
Table A – lessons
Lesson_id:1
Lesson_class_id: 22
Lesson_date: 2019-09-01
Lesson_term: Autumn 2019
Table B- registers
Register_id:1
Register_lesson_id:1
Register_student_id:33
Register_status: NULL
Register_update_by: NULL
Register_update_dat: NULL
Register_id:2
Register_lesson_id:1
Register_student_id:44
Register_status: NULL
Register_update_by: NULL
Register_update_dat: NULL
…
Table C- Backup
Lesson_id: 555
Lesson_class_id: 1
Lesson_date: 2019-09-01
Lesson_term: Autumn 2019
Register_id: 666
Register_lesson_id: 1
Register_student_id: 33
Register_status: Present
Register_update_by: TeacherX
Register_update_date: 2019-09-02
Lesson_id: 556
Lesson_class_id: 1
Lesson_date: 2019-09-01
Lesson_term: Autumn 2019
Register_id: 667
Register_lesson_id: 1
Register_student_id: 44
Register_status: Late
Register_update_by: TeacherX
Register_update_date: 2019-09-02