Mysql

用一條語句更新表中的許多行?

  • September 13, 2017

更新表中多行的最簡單方法是什麼?我有一個如下所示的 csv 文件:

|primary_key |value|
|          1 |  xyz|
|          2 |  abc|
|          3 |  def|
...

目標表中已存在具有這些主鍵的行

我想用這些值更新目標表。是否有語法,以便我可以編寫如下內容:

update mytable set value = ('xyz', 'abc', 'def') where primary key = (1,2,3);

通過MySQL 更新參考,這個站點(MySQL-csv 更新),SO(更新多行多個數據庫更新更新多行),我懷疑答案是“否”,但我想確認一下是真的。

首先是樣本數據

mysql> drop table if exists mytable;
Query OK, 0 rows affected (0.03 sec)

mysql> create table mytable
   -> (
   ->     id int not null,
   ->     value VARCHAR(255),
   ->     primary key (id)
   -> );
Query OK, 0 rows affected (0.06 sec)

mysql> insert into mytable (id) values (1),(2),(3);
Query OK, 3 rows affected (0.06 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from mytable;
+----+-------+
| id | value |
+----+-------+
|  1 | NULL  |
|  2 | NULL  |
|  3 | NULL  |
+----+-------+
3 rows in set (0.00 sec)

mysql>

這是新的查詢

update mytable A inner join
(
   SELECT 1 id,'xyz' value UNION
   SELECT 2   ,'abc'       UNION
   SELECT 3   ,'def'

) B USING (id)
SET A.value = B.value;

這是執行的新查詢

mysql> update mytable A inner join
   -> (
   ->     SELECT 1 id,'xyz' value UNION
   ->     SELECT 2   ,'abc'       UNION
   ->     SELECT 3   ,'def'
   -> ) B USING (id)
   -> SET A.value = B.value;
Query OK, 0 rows affected (0.06 sec)
Rows matched: 3  Changed: 0  Warnings: 0

mysql> select * from mytable;
+----+-------+
| id | value |
+----+-------+
|  1 | xyz   |
|  2 | abc   |
|  3 | def   |
+----+-------+
3 rows in set (0.00 sec)

mysql>

引用自:https://dba.stackexchange.com/questions/15696