在 MySQL 中交換兩個列值?


要交換兩列,我們可以應用以下交換邏輯。

  • 將兩個值相加並存儲到第一列

  • 從第二列減去第一列的值並將其儲存到第二列。

  • 從第一列減去更新的第二列的值並將其儲存到第一列。

上述規則結構如下。假設,第一列為 a,第二列為 b。

1. a = a+b;
2. b = a-b;
3. a = a-b;

現在,我們將應用上述規則來交換兩個列值。

建立表。

mysql> create table SwappingTwoColumnsValueDemo
   -> (
   -> FirstColumnValue int,
   -> SecondColumnValue int
   -> );
Query OK, 0 rows affected (0.49 sec)

插入一些記錄。

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

交換前檢查列值。

mysql> select *from SwappingTwoColumnsValueDemo;

以下是輸出內容。

+------------------+-------------------+
| FirstColumnValue | SecondColumnValue |
+------------------+-------------------+
|               10 |                20 |
|               30 |                40 |
|               50 |                60 |
|               70 |                80 |
|               90 |               100 |
+------------------+-------------------+
5 rows in set (0.00 sec)

交換列值的語法。

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

檢查列值是否已交換。

mysql> select *from SwappingTwoColumnsValueDemo;

以下是輸出內容。

+------------------+-------------------+
| FirstColumnValue | SecondColumnValue |
+------------------+-------------------+
|               20 |                10 |
|               40 |                30 |
|               60 |                50 |
|               80 |                70 |
|              100 |                90 |
+------------------+-------------------+
5 rows in set (0.00 sec)

更新於: 30-Jul-2019

7k+ 瀏覽

開啟你的 職業生涯

完成課程獲得證書

開始
廣告