Skip to content

Instantly share code, notes, and snippets.

@sshaw
Created July 16, 2012 07:33
Show Gist options
  • Save sshaw/3121370 to your computer and use it in GitHub Desktop.
Save sshaw/3121370 to your computer and use it in GitHub Desktop.
MySQL Update via Swap
mysql> create table t (id int, v1 int, v2 int);
Query OK, 0 rows affected (0.05 sec)
mysql> insert into t values (1,100,200),(2,101,201),(3,102,202);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from t;
+------+------+------+
| id | v1 | v2 |
+------+------+------+
| 1 | 100 | 200 |
| 2 | 101 | 201 |
| 3 | 102 | 202 |
+------+------+------+
3 rows in set (0.00 sec)
mysql> update t join t tmp on tmp.id = t.id set t.v1 = t.v2, t.v2 = tmp.v1 where t.id in (1,2);
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from t;
+------+------+------+
| id | v1 | v2 |
+------+------+------+
| 1 | 200 | 100 |
| 2 | 201 | 101 |
| 3 | 102 | 202 |
+------+------+------+
3 rows in set (0.00 sec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment