Mysql: Swap data for different rows

前端 未结 4 1287
感情败类
感情败类 2020-12-14 03:11

Suppose a table fruits that looks like this:

------------------------------------------
| id |    name    |   color   | calories |
-------------         


        
相关标签:
4条回答
  • 2020-12-14 03:46

    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;
    
    0 讨论(0)
  • 2020-12-14 03:49

    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/#!18/27318a/5

    0 讨论(0)
  • 2020-12-14 03:50

    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.

    0 讨论(0)
  • 2020-12-14 03:53

    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.

    0 讨论(0)
提交回复
热议问题