如何按條件來排序並選擇 MySQL 中的查詢?


以下是語法 −

select * from yourTableName order by yourColumnName=0,yourColumnName;

我們首先建立一個表 −

mysql> create table DemoTable1348
   -> (
   -> Amount int
   -> );
Query OK, 0 rows affected (0.80 sec)

使用 insert 命令在該表中插入一些記錄 −

mysql> insert into DemoTable1348 values(100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1348 values(45);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1348 values(0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(89);
Query OK, 1 row affected (0.12 sec)

使用 select 語句從該表中顯示所有記錄 −

mysql> select * from DemoTable1348;

這會生成以下輸出 −

+--------+
| Amount |
+--------+
|    100 |
|      0 |
|     90 |
|     45 |
|      0 |
|     89 |
+--------+
6 rows in set (0.00 sec)

以下是對帶有條件的查詢進行排序和選擇的查詢 −

mysql> select * from DemoTable1348 order by Amount=0,Amount;

這會生成以下輸出 −

+--------+
| Amount |
+--------+
|     45 |
|     89 |
|     90 |
|    100 |
|      0 |
|      0 |
+--------+
6 rows in set (0.00 sec)

更新於: 05-11-2019

189 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.