-
SQL > UPDATE à partir d’une autre table avec jointures
Le but est de mettre à jour les données d’une table (
TABLE_A) à partir des données d’une autre table (TABLE_B).+-----------------------------+ +-----------------------------+ | TABLE_A | | TABLE_B | +-----------------------------+ +-----------------------------| | col_1 | col_2 | col_3 | | col_1 | col_2 | col_3 | +---------+---------+---------+ +----------+-------+----------+ | 1 | | | | 7 | A | | | 2 | | | | 3 | B | | | 3 | | | | 5 | C | | | 4 | | | | 3 | D | | | 5 | | | | 7 | E | | | 6 | | | | 9 | F | | | 7 | | | | 4 | G | | | 8 | | | | 6 | H | | | 9 | | | | 7 | I | | +---------+---------+---------+ +----------+-------+----------+ ^ | |______________________|
Syntaxe
UPDATE nom_table_à_updater AS t1 INNER JOIN nom_table_2 AS t2 ON t1.nom_colonne1 = t2. nom_colonne1 SET t1.nom_colonne2 = t2.nom_colonne2;
nom_table1Nom de la table dans laquelle les mises à jour seront effectuéesnom_table2Nom de la table dans laquelle sera prises les donnéest1.nom_colonne1Nom de la colonne où se fera le lien des deux tablest1.nom_colonne2Nom de la colonne où seront prises les donnéesExemple
UPDATE student_marks AS t1 INNER JOIN student_profile AS t2 ON t1.student_id = t2.student_id SET t1.student_name = t2.student_name;
On peut bien évidemment ajouter des conditions
WHEREet autres.UPDATE student_marks AS t1 INNER JOIN student_profile AS t2 ON t1.student_id = t2.student_id SET t1.student_name = t2.student_name WHERE t1.student_id <= 100;