使用 MySQL,我能否對列進行排序,但將 0 放在最後?


您可以使用 ORDER BY 對列進行排序,讓 0 位於最後。語法如下 -

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

為了理解上述概念,讓我們建立一個表。建立表的查詢如下 -

mysql> create table SortColumnZeroAtLastDemo
   −> (
   −> RankNumber int
   −> );
Query OK, 0 rows affected (1.40 sec)

現在,您可以使用以下查詢在表中插入記錄 -

mysql> insert into SortColumnZeroAtLastDemo values(100);
Query OK, 1 row affected (0.20 sec)

mysql> insert into SortColumnZeroAtLastDemo values(0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into SortColumnZeroAtLastDemo values(0);
Query OK, 1 row affected (0.11 sec)

mysql> insert into SortColumnZeroAtLastDemo values(50);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SortColumnZeroAtLastDemo values(10);
Query OK, 1 row affected (0.15 sec)

mysql> insert into SortColumnZeroAtLastDemo values(0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into SortColumnZeroAtLastDemo values(40);
Query OK, 1 row affected (0.12 sec)

使用 select 語句從表中顯示所有記錄。查詢如下 -

mysql> select *from SortColumnZeroAtLastDemo;

以下是輸出 -

+------------+
| RankNumber |
+------------+
|        100 |
|          0 |
|          0 |
|         50 |
|         10 |
|          0 |
|         40 |
+------------+
7 rows in set (0.00 sec)

以下是使用我們在開頭討論的語法對列進行排序並將值 0 設定為最後的查詢 -

mysql> select *from SortColumnZeroAtLastDemo order by RankNumber = 0,RankNumber;

以下是輸出 -

+------------+
| RankNumber |
+------------+
|         10 |
|         40 |
|         50 |
|        100 |
|          0 |
|          0 |
|          0 |
+------------+
7 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

58 次瀏覽

開啟您的職業之旅

透過完成課程獲得認證

開始
廣告