47
$query = mysql_query("UPDATE a SET fruit = '**apple**' WHERE id = '**1**' ");
$query2 = mysql_query("UPDATE a SET fruit = '**orange**' WHERE id = '**2**' ");
$query3 = mysql_query("UPDATE a SET fruit = '**peach**' WHERE id = '**3**' ");

有没有办法将其简化为一个查询?

4

4 回答 4

65

我找到了以下解决方案:

INSERT into `table` (id,fruit)
    VALUES (1,'apple'), (2,'orange'), (3,'peach')
    ON DUPLICATE KEY UPDATE fruit = VALUES(fruit);

Id 必须是唯一的或主键。但不知道性能。

于 2013-09-24T13:46:06.870 回答
64

是的,您可以使用以下查询来做到这一点:

UPDATE a 
SET fruit = (CASE id WHEN 1 THEN 'apple'
                     WHEN 2 THEN 'orange'
                     WHEN 3 THEN 'peach'
             END)
WHERE id IN(1,2 ,3);
于 2012-07-26T07:51:01.940 回答
1

根据警告信息

'VALUES function' is deprecated and will be removed in a future release. Please use an alias (INSERT INTO ... VALUES (...) AS alias) and replace VALUES(col) in the ON DUPLICATE KEY UPDATE clause with alias.col instead

可以考虑对Yaroslav的解决方案进行轻微修改,如下所示:

INSERT into `table` (id,fruit)
VALUES (1,'apple'), (2,'orange'), (3,'peach') as tb
ON DUPLICATE KEY UPDATE fruit = tb.fruit;

它做同样的事情,但使警告消息静音。

于 2020-07-31T16:06:05.960 回答
1

在 MySQL 中使用 IF() 函数可以实现为

UPDATE a
SET fruit = IF (id = 1, 'apple', IF (id = 2, 'orange', IF (id = 3, 'peach', fruit)));
于 2020-03-02T20:55:14.417 回答