Logic hoán đổi không dùng biến tạm:
1. a = a + b 2. b = a - b (lúc này a = a+b, nên b = a+b-b = a) 3. a = a - b (lúc này b = a cũ, a = a+b-a = b cũ)
Tạo bảng
mysql> CREATE TABLE SwappingTwoColumnsValueDemo (
-> FirstColumnValue INT,
-> SecondColumnValue INT
-> );
Query OK, 0 rows affected (0.49 sec)
Chèn dữ liệu
mysql> INSERT INTO SwappingTwoColumnsValueDemo VALUES
-> (10,20),(30,40),(50,60),(70,80),(90,100);
Query OK, 5 rows affected (0.19 sec)
mysql> SELECT * FROM SwappingTwoColumnsValueDemo;
+------------------+-------------------+ | FirstColumnValue | SecondColumnValue | +------------------+-------------------+ | 10 | 20 | | 30 | 40 | | 50 | 60 | | 70 | 80 | | 90 | 100 | +------------------+-------------------+ 5 rows in set (0.00 sec)
Thực hiện hoán đổi
mysql> UPDATE SwappingTwoColumnsValueDemo
-> SET FirstColumnValue = FirstColumnValue + SecondColumnValue,
-> SecondColumnValue = FirstColumnValue - SecondColumnValue,
-> FirstColumnValue = FirstColumnValue - SecondColumnValue;
Query OK, 5 rows affected (0.15 sec)
mysql> SELECT * FROM SwappingTwoColumnsValueDemo;
+------------------+-------------------+ | FirstColumnValue | SecondColumnValue | +------------------+-------------------+ | 20 | 10 | | 40 | 30 | | 60 | 50 | | 80 | 70 | | 100 | 90 | +------------------+-------------------+ 5 rows in set (0.00 sec)
Hai cột đã đổi chỗ giá trị thành công.