如何從 select 查詢中新增一列,但是新列的值將是 MySQL select 查詢的行數?


為此,你可以使用 MySQL row_number()。我們首先建立一個表格 −

mysql> create table DemoTable1342
   -> (
   -> Score int
   -> );
Query OK, 0 rows affected (0.68 sec)

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

mysql> insert into DemoTable1342 values(80);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1342 values(98);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1342 values(78);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1342 values(89);
Query OK, 1 row affected (0.07 sec)

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

mysql> select * from DemoTable1342;

這將產生以下輸出 −

+-------+
| Score |
+-------+
|    80 |
|    98 |
|    78 |
|    89 |
+-------+
4 rows in set (0.00 sec)

以下是新增一列來自 select 查詢,但是新列的值將是 MySQL select 查詢的行數的查詢 −


mysql> select Score,row_number() over() as `Rank` from DemoTable1342 order by Score DESC;

這將產生以下輸出 −

+-------+------+
| Score | Rank |
+-------+------+
|    98 |    1 |
|    89 |    2 |
|    80 |    3 |
|    78 |    4 |
+-------+------+
4 rows in set (0.32 sec)

更新於: 2019 年 11 月 5 日

271 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告