开发者

Swapping values within same table with MySQL

I have a really weird situation. I need to swap a column value between two rows in the same table so I use (where s1 and s2 are the two rows)

UPDATE table s1, table s2 
SET s1.data = s2.data, s2.data = @temp
WHERE @temp:=s1.data AND [some expression that works]
ORDER BY s2.data ASC
LIMIT 1

This generates an error Incorrect usage of UPDATE and ORDER BY

I just want to find the entry from the table that have the closest smaller data entry to the original entry and swap the two values. Doing

SELECT * FROM table s1, table s2
WHERE [the same expression that works]
ORDER BY s2.data ASC
LIMIT 1

Returns a table with the require开发者_运维百科d results, but the mentioned UPDATE does not work. What am I getting wrong?


Apparently what I want cannot be done in one MySQL query. I ended up doing 3 queries, one SELECT and two UPDATE for each of the columns and using temporary variables in PHP. I guess it can be also done in three consecutive queries in MySQL with MySQL temporary variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜