如何使用单个查询更新两行的交换值

时间:2010-12-23 09:04:41

标签: mysql swap

是否有查询可以用单个查询交换两行的值?

2 个答案:

答案 0 :(得分:25)

您可以在本文中看到解决方案

http://www.microshell.com/database/sql/swap-values-in-2-rows-sql/

查看:优雅的方式,进行连接以获取2行中的数据,将其换成1行,之后进行更新很容易。

示例:

UPDATE
rules AS rule1
JOIN rules AS rule2 ON
( rule1.rule_id = 1 AND rule2.rule_id = 4 )
SET
rule1.priority = rule2.priority,
rule2.priority = rule1.priority
;

答案 1 :(得分:10)

UPDATE my_table SET a=@tmp:=a, a=b, b=@tmp;