MySQL table association update

background:

There are two tables, a class information table and a student information table, but the information in the student table is wrong, and the information in the class table needs to be used to update the student table data.

Insert image description here

 Insert image description here

 
method one:

update student_info s 
set class_name = (select class_name from class_info where class_id = s.class_id)

[Result]: If the data is associated through the associated field, the content will be updated accordingly; if it is not associated, the content will become null.


Method Two:

update student_info s, class_info c set s.class_name = c.class_name
where s.class_id = c.class_id

[Result]: For data associated through associated fields, the content will be updated accordingly; for data that is not associated, the content will remain unchanged.


Method 3 (not recommended):

update student_info s
left join class_info c on s.class_id = c.class_id
set s.class_name = c.class_name


[Result]: If the data is associated through the associated field, the content will be updated accordingly; if it is not associated, the content will become null.

[Note]: The writing method of left join is easy to write incorrectly, which will cause the information associated with the left table to be updated. The same is true for right join. The writing method of join is similar to method two, so the result is also the same as method two.

Guess you like

Origin blog.csdn.net/LiZhen314/article/details/131807926