MySQL 查询在 SELECT 语句中生成行索引(排名)?
mysqlmysqli database
要生成行索引,请使用 ROW_NUMBER()。让我们首先创建一个表 −
mysql> create table DemoTable ( Name varchar(40) ); Query OK, 0 rows affected (0.49 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.08 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+--------+ | Name | +--------+ | Chris | | Chris | | Chris | | Robert | | Robert | | Adam | | Adam | | Adam | | Adam | +--------+ 9 rows in set (0.00 sec)
以下是在 MySQL SELECT 语句中生成行索引的查询。在这里,我们为重复名称设置了等级 −
mysql> select Name, row_number() over (partition by Name) as `Rank` from DemoTable;
这将产生以下输出 −
+--------+------+ | Name | Rank | +--------+------+ | Adam | 1 | | Adam | 2 | | Adam | 3 | | Adam | 4 | | Chris | 1 | | Chris | 2 | | Chris | 3 | | Robert | 1 | | Robert | 2 | +--------+------+ 9 rows in set (0.00 sec)