【バルクアップサート】MySQLで一括でUPSERTする方法

2019年8月30日DB, SQL, wordpressMySQL, tips

構文

普通のupsert文のupdate部分でVALUES(カラム名)を指定すればいいようです。

INSERT INTO 
  tablename(col_name1, col_name2) 
VALUES (1, "hoge"), (2, "fuga")
ON DUPLICATE KEY UPDATE
  col_name2 = VALUES(`col_name2`);

具体例

mysql> create table user( userid int(11) primary key not null , nickname varchar(100) not null );                                                                                                                     
Query OK, 0 rows affected (0.05 sec) 
mysql> desc user; 
+----------+--------------+------+-----+---------+-------+ 
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| userid   | int(11)      | NO   | PRI | NULL    |       |
| nickname | varchar(100) | NO   |     | NULL    |       |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> insert into user values (1, "user1"); 
Query OK, 1 row affected (0.02 sec) 
mysql> select * from user; 
+--------+----------+
| userid | nickname |
+--------+----------+
|      1 | user1    |
+--------+----------+
1 row in set (0.00 sec)
mysql> insert into user values (1, "enutake"), (2, "pmarusama"), (3, "nanamori") on duplicate key update nickname = values(`nickname`); 
Query OK, 4 rows affected (0.02 sec) 
Records: 3  Duplicates: 1  Warnings: 0
mysql> select * from user;
+--------+-----------+ 
| userid | nickname  |
+--------+-----------+
|      1 | enutake   |
|      2 | pmarusama |
|      3 | nanamori  |
+--------+-----------+
3 rows in set (0.00 sec)

これでSQL発行数が減らせて効率的なupsertができます。

サイト運営者 えぬたけ


都内で働くゆるふわフルスタックwebエンジニア。