• 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_table1 Nom de la table dans laquelle les mises à jour seront effectuées

      nom_table2 Nom de la table dans laquelle sera prises les données

      t1.nom_colonne1 Nom de la colonne où se fera le lien des deux tables

      t1.nom_colonne2 Nom de la colonne où seront prises les données

      Exemple

      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 WHERE et 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;

 

Aucun commentaire

 

Laissez un commentaire