Vấn đề
Cập nhật cột StudentScore trong DemoTable2 bằng giá trị Value từ DemoTable1 nơi PersonId = StudentId.
Giải pháp: UPDATE JOIN (MySQL syntax)
UPDATE DemoTable1, DemoTable2 SET DemoTable2.StudentScore = DemoTable1.Value WHERE DemoTable2.StudentId = DemoTable1.PersonId;
Ví dụ minh họa
Bảng nguồn DemoTable1
mysql> CREATE TABLE DemoTable1 (PersonId INT, Value INT);
mysql> INSERT INTO DemoTable1 VALUES (100, 78), (101, 67), (102, 89);
Bảng đích DemoTable2 (StudentScore NULL)
mysql> CREATE TABLE DemoTable2 (StudentId INT, StudentScore INT);
mysql> INSERT INTO DemoTable2 VALUES (100, NULL), (102, NULL);
UPDATE JOIN
mysql> UPDATE DemoTable1, DemoTable2 SET DemoTable2.StudentScore = DemoTable1.Value WHERE DemoTable2.StudentId = DemoTable1.PersonId;
Query OK, 2 rows affected (0.13 sec)
Kết quả
mysql> SELECT * FROM DemoTable2;
+-----------+--------------+ | StudentId | StudentScore | +-----------+--------------+ | 100 | 78 | | 102 | 89 | +-----------+--------------+
Cú pháp chuẩn SQL: UPDATE ... JOIN ... ON
UPDATE DemoTable2 t2 JOIN DemoTable1 t1 ON t2.StudentId = t1.PersonId SET t2.StudentScore = t1.Value;
Khuyến nghị dùng cú pháp này (rõ ràng, chuẩn ANSI, dễ đọc).
Lưu ý
- Chỉ cập nhật dòng có khớp (INNER JOIN). Dòng không khớp không đổi.
- Nếu cần cập nhật cả dòng không khớp (SET NULL), dùng LEFT JOIN.
- Đảm bảo cột join có index để nhanh.
- Backup trước khi UPDATE production.