如何在 MySQL 中交换特定字段值?
首先让我们创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Number1 int, Number2 int ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(Number1,Number2) values(10,30); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Number1,Number2) values(60,50); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Number1,Number2) values(110,100); Query OK, 1 row affected (0.10 sec)
使用 select 语句从表中显示所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 10 | 30 | | 2 | 60 | 50 | | 3 | 110 | 100 | +----+---------+---------+ 3 rows in set (0.00 sec)
现在让我们交换 MySQL 中的一个特定字段值。这里,我们将交换 Id=2 的字段 “Number1” 和 “Number2” −
mysql> update DemoTable set Number1=(@temporaryVariable:=Number1), Number1=Number2, Number2=@temporaryVariable where Id=2; Query OK, 1 row affected (0.21 sec) Rows matched: 1 Changed: 1 Warnings: 0
让我们再次检查表记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+----+---------+---------+ | Id | Number1 | Number2 | +----+---------+---------+ | 1 | 10 | 30 | | 2 | 50 | 60 | | 3 | 110 | 100 | +----+---------+---------+ 3 rows in set (0.00 sec)
广告