En algunas ocasiones, por algún motivo nos puede interesar intercambiar los valores de una columna por los de otra. Escenificando un poco más, partimos de la siguiente tabla test, en la que queremos intercambiar los valores de la columna long por los de la columna lat.
mysql> show create table test; +-------+---------------------------------+ | Table | Create Table | +-------+---------------------------------+ | users | CREATE TABLE `test` ( | | | `id` int(11) DEFAULT '0', | | | `name` varchar(100) DEFAULT '', | | | `long` int(11) DEFAULT NULL, | | | `lat` int(11) DEFAULT NULL, | | | ) ENGINE=InnoDB | +-------+---------------------------------+ mysql> select * from test; +----+------+------+------+ | id | name | long | lat | +----+------+------+------+ | 1 | x | -1 | 1 | | 2 | y | -2 | 2 | | 3 | z | -3 | 3 | +----+------+------+------+ 3 rows in set (0.00 sec)
Para realizarlo no sirve con lanzar un update del estilo,
mysql>update test set long=lat,lat=long;
ya que mysql no permite realizar este tipo de updates. Para solucionar este problema, el update necesario sería el que sigue tras el salto.
mysql> update test t1,test t2 set t1.long=t2.lat, t1.lat=t2.long where t1.id=t2.id; Query OK, 3 rows affected (0.04 sec) Rows matched: 3 Changed: 3 Warnings: 0 mysql> select * from test; +----+------+------+------+ | id | name | long | lat | +----+------+------+------+ | 1 | x | 1 | -1 | | 2 | x | 2 | -2 | | 3 | x | 3 | -3 | +----+------+------+------+ 3 rows in set (0.00 sec)
Si los campos son de tipo VARCHAR, entonces también se podría realizar utilizando una variable temporal de mysql, y filtrando que los campos nunca estén a NULL.
mysql> update test set long=lat, lat=@temp where (@temp:=long) IS NOT NULL;
En mariadb funciona perfectamente, aunque no es de extrañar.
ResponderEliminar