您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在MySQL中交换两列的值?

2024/3/16 18:02:36发布26次查看
to swap two columns, we can apply the below swapping logic.
add both values and store them into the first column
subtract the first column’s value from the second and store it into the second column.
subtract the first column’s value from the updated second column and store it into the first.
the above rule structure is as follows. suppose, the first column is a and the second column is b.
1. a = a+b;2. b = a-b;3. a = a-b;
now we will apply the above rule in order to swap the two column values.
creating a table.
mysql> create table swappingtwocolumnsvaluedemo   -> (   -> firstcolumnvalue int,   -> secondcolumnvalue int   -> );query ok, 0 rows affected (0.49 sec)
inserting some records.
mysql>  insert into swappingtwocolumnsvaluedemo values(10,20),(30,40),(50,60),(70,80),(90,100);query ok, 5 rows affected (0.19 sec)records: 5  duplicates: 0  warnings: 0
to check the column values before swapping.
mysql> select *from swappingtwocolumnsvaluedemo;

the following is the output.
+------------------+-------------------+| firstcolumnvalue | secondcolumnvalue |+------------------+-------------------+|               10 |    20 ||               30 |    40 ||               50 |    60 ||               70 |    80 ||               90 |   100 |+------------------+-------------------+5 rows in set (0.00 sec)
syntax to swap column values.
mysql> update swappingtwocolumnsvaluedemo   -> set firstcolumnvalue = firstcolumnvalue+secondcolumnvalue,   -> secondcolumnvalue = firstcolumnvalue-secondcolumnvalue,   -> firstcolumnvalue = firstcolumnvalue-secondcolumnvalue;query ok, 5 rows affected (0.15 sec)rows matched: 5  changed: 5 warnings: 0
to check if the column values have been swapped or not.
mysql> select *from swappingtwocolumnsvaluedemo;

the following is the output.
+------------------+-------------------+| firstcolumnvalue | secondcolumnvalue |+------------------+-------------------+|               20 |    10 ||               40 |    30 ||               60 |    50 ||               80 |    70 ||              100 |      90 |+------------------+-------------------+5 rows in set (0.00 sec)
以上就是在mysql中交换两列的值?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product