Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Thay đổi thứ tự các mục trong MySQL

Thay đổi thứ tự các mục trong MySQL

Để thay đổi thứ tự các mục trong MySQL, hãy sử dụng ORDER BY tên bí danh (alias). Hãy tạo một bảng trước:

mysql> create table DemoTable653 (Product1Amount int, Product2Amount int);
Query OK, 0 rows affected (0.42 sec)

Chèn một số bản ghi vào bảng bằng lệnh insert:

mysql> insert into DemoTable653 values(400,250);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable653 values(500,300);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable653 values(40,400);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable653 values(200,450);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable653 values(50,20);
Query OK, 1 row affected (0.10 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:

mysql> select * from DemoTable653;

Điều này sẽ tạo ra đầu ra sau:

+----------------+----------------+
| Product1Amount | Product2Amount |
+----------------+----------------+
|            400 |            250 |
|            500 |            300 |
|             40 |            400 |
|            200 |            450 |
|             50 |             20 |
+----------------+----------------+
5 rows in set (0.00 sec)

Truy vấn sau thay đổi thứ tự các mục và hiển thị sự chênh lệch:

mysql> select Product1Amount, Product2Amount, (Product1Amount-Product2Amount) as ProductAmountDifference from DemoTable653 order by ProductAmountDifference;

Điều này sẽ tạo ra đầu ra sau:

+----------------+----------------+-------------------------+
| Product1Amount | Product2Amount | ProductAmountDifference |
+----------------+----------------+-------------------------+
|             40 |            400 |                    -360 |
|            200 |            450 |                    -250 |
|             50 |             20 |                      30 |
|            400 |            250 |                     150 |
|            500 |            300 |                     200 |
+----------------+----------------+-------------------------+
5 rows in set (0.29 sec)