使用单个语句更新表中的许多行?


9

更新表中许多行的最简单方法是什么?我有一个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标签,假设您对MySQL文档的引用隐含了您正在使用的数据库。
贾斯汀·凯夫

Answers:


10

首先是示例数据

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>

UPDATE table INNER JOIN ... USING(id) SET ...太棒了
NinoŠkopac

3

假设您不想将数据从CSV文件加载到数据库表中,然后执行相关操作UPDATE

UPDATE mytable t
   SET value = (SELECT value
                  FROM tbl_with_csv_data csv
                 WHERE csv.primary_key = t.primary_key)
 WHERE EXISTS( SELECT 1
                 FROM tbl_with_csv_data csv
                 WHERE csv.primary_key = t.primary_key)

那么您应该可以使用 CASE

UPDATE mytable t
   SET value = CASE WHEN primary_key = 1 THEN 'xyz'
                    WHEN primary_key = 2 THEN 'abc'
                    WHEN primary_key = 3 THEN 'def'
                    ELSE value
                END
 WHERE primary_key IN (1,2,3);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.