可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Suppose a table fruits
that looks like this:
------------------------------------------ | id | name | color | calories | ------------------------------------------ | 1 | apple | red | 20 | | 2 | orange | orange | 10 | | 3 | grapes | green | 5 | | 4 | bananas | yellow | 15 | | 5 | plum | purple | 25 | ------------------------------------------
How can I swap the values of a row, with another, leaving the id number intact?
Example:
SWAP ROW WITH ID "5" WITH ROW WITH ID "2"
Result:
------------------------------------------ | id | name | color | calories | ------------------------------------------ | 1 | apple | red | 20 | | 2 | plum | purple | 25 | | 3 | grapes | green | 5 | | 4 | bananas | yellow | 15 | | 5 | orange | orange | 10 | ------------------------------------------
Note that all the values are intact except for the id. I need to do this with a really large list of values, so I need a one-liner, or at most, something that doesn't require the creation of temporary tables, and things like that.
Note: id is unique
Thank you
回答1:
You could use a join inequality to line up the rows you want to swap:
update fruit a inner join fruit b on a.id b.id set a.color = b.color, a.name = b.name, a.calories = b.calories where a.id in (2,5) and b.id in (2,5)
http://sqlfiddle.com/#!2/18b9c/1
回答2:
Since ID is unique, it is difficult to just swap the IDs, it's easier to swap the column contents. A query like this might be what you need:
UPDATE yourtable t1 INNER JOIN yourtable t2 ON (t1.id, t2.id) IN ((1,5),(5,1)) SET t1.color = t2.color, t1.name = t2.name, t1.calories = t2.calories
Please see fiddle here.
回答3:
Here's a way to store values temporarily without using a temp table or a dummy row in your fruit table:
SELECT name, color, calories FROM fruit WHERE id = 2 INTO @name, @color, @calories; UPDATE fruit AS f1, fruit AS f2 SET f1.name = f2.name, f2.name = @name, f1.color = f2.color, f2.color = @color, f1.calories = f2.calories, f2.calories = @calories WHERE (f1.id, f2.id) = (2, 5);
Here's another solution that uses a dummy id value:
UPDATE fruit SET id = 0 WHERE id = 5; UPDATE fruit SET id = 5 WHERE id = 2; UPDATE fruit SET id = 2 WHERE id = 0;
回答4:
If your operations are based on ID, and you want to swap entire rows, a fancy way of swapping UNIQUE IDs is to start numbering them at 1, and use 0 as a temporary value.
Another way of performing this is using an unsigned column, and using a designated value (ie.: -1) for temporary. I wouldn't really recommend the latter, as we are effectively wasting space with this method. See http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html for more details.