$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**' ");
有没有办法将其简化为一个查询?
答案 0 :(得分:57)
我找到了以下解决方案:
INSERT into `table` (id,fruit)
VALUES (1,'apple'), (2,'orange'), (3,'peach')
ON DUPLICATE KEY UPDATE fruit = VALUES(fruit);
Id必须是唯一或主键。 但不了解表现。
答案 1 :(得分:50)
是的,您可以使用此查询执行此操作:
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);
答案 2 :(得分: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;
它执行相同的操作,但是忽略警告消息。
答案 3 :(得分:0)
在MySQL中使用IF()函数可以实现为
POST