TIL

Today I Learned. 知ったこと、学んだことを書いていく

【MySQL】 TBL2のレコードの値によって、TBL1のレコードをUPDATEする

  • 以下のようなデータを用意
CREATE TABLE table1(id int not null, name varchar (15)); 
CREATE TABLE table2(id int not null, gender char (1));

INSERT INTO table1 VALUES (1, 'takuya');
INSERT INTO table1 VALUES (2, 'taro');
INSERT INTO table1 VALUES (3, 'jiro');
INSERT INTO table1 VALUES (4, 'saburo');
INSERT INTO table1 VALUES (5, 'siro');

insert into table2 values (1, 1);
insert into table2 values (2, 2);
insert into table2 values (3, 1);
insert into table2 values (4, 2);
insert into table2 values (5, 2);
mysql> select * from table1;
+----+--------+
| id | name   |
+----+--------+
|  1 | takuya |
|  2 | taro   |
|  3 | jiro   |
|  4 | saburo |
|  5 | siro   |
+----+--------+
5 rows in set (0.00 sec)

mysql> select * from table2;
+----+--------+
| id | gender |
+----+--------+
|  1 | 1      |
|  2 | 2      |
|  3 | 1      |
|  4 | 2      |
|  5 | 2      |
+----+--------+
5 rows in set (0.00 sec)

複数テーブルを使ったUPDATE文の実行をしてみる

カンマを使う場合

table2.gender = 2のレコードと紐づくtable1のデータの値を更新してみる

update table1
, (select * from table2 where gender = 2) tbl2 
set
  table1.name = 'gender2' 
where
  table1.id = tbl2.id;
  • 結果は以下のようになる
mysql> select table1.id, table1.name, table2.gender from table1 left join table2 on table1.id = table2.id;
+----+---------+--------+
| id | name    | gender |
+----+---------+--------+
|  1 | takuya  | 1      |
|  2 | gender2 | 2      |
|  3 | jiro    | 1      |
|  4 | gender2 | 2      |
|  5 | gender2 | 2      |
+----+---------+--------+
5 rows in set (0.00 sec)

カンマを使わない場合

update table1 
  inner join (select * from table2 where gender = 2) tbl2 
    on table1.id = tbl2.id 
set
  table1.name = 'gender2'

inner joinを使っているところに注意する
もし、left joinにしてしまうと、table1の全レコードがupdateされてしまう

参考文献