可將特定記錄置頂的 MySQL 查詢


為此,你可以使用 ORDER BY CASE 語句。我們先建立一個表 −

mysql> create table DemoTable
(
   StudentName varchar(100),
   StudentMarks int
);
Query OK, 0 rows affected (0.97 sec)

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

mysql> insert into DemoTable values('Chris',45);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('John',67);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('David',89);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable values('John',98);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Mike',79);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John',99);
Query OK, 1 row affected (0.11 sec)

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

mysql> select *from DemoTable;

將生成以下輸出 −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           45 |
| John        |           67 |
| David       |           89 |
| John        |           98 |
| Mike        |           79 |
| John        |           99 |
+-------------+--------------+
6 rows in set (0.00 sec)

以下是將特定記錄置頂的查詢 −

mysql> select *from DemoTable order by case StudentName when 'John' then 2 else 3 end, StudentName, StudentMarks;

將生成以下輸出 −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| John        |           67 |
| John        |           98 |
| John        |           99 |
| Chris       |           45 |
| David       |           89 |
| Mike        |           79 |
+-------------+--------------+
6 rows in set (0.00 sec)

更新於: 27-Sep-2019

140 次瀏覽

啟動你的職業生涯

完成課程以獲得認證

開始吧
廣告
© . All rights reserved.