根據條件在 MySQL 中對記錄進行排序


為此,你可以使用 ORDER BY IF()。我們首先建立一個表 −

mysql> create table DemoTable
(
   Name varchar(50),
   Score int
);
Query OK, 0 rows affected (0.72 sec)

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

mysql> insert into DemoTable values('Chris',98);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('David',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Bob',56);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Carol',78);
Query OK, 1 row affected (0.14 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這將生成以下輸出 −

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    98 |
| David |    45 |
| Bob   |    56 |
| Sam   |    89 |
| Carol |    78 |
+-------+-------+
5 rows in set (0.00 sec)

以下是根據條件在 MySQL 中對記錄進行排序的查詢 −

mysql> select *from DemoTable order by if(Name='Sam',1,0) ASC,Score DESC;

這將生成以下輸出 −

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    98 |
| Carol |    78 |
| Bob   |    56 |
| David |    45 |
| Sam   |    89 |
+-------+-------+
5 rows in set (0.00 sec)

更新於:2019 年 10 月 3 日

878 次瀏覽

開啟你的 職業

完成課程以取得認證

開始
廣告
© . All rights reserved.