MySQL查询显示多列的排名?
为此,请使用FIND_IN_SET()方法。让我们首先创建一个表-
mysql> create table DemoTable634 (FirstName varchar(100),Marks int,Age int);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable634 values('John',60,23); mysql> insert into DemoTable634 values('Chris',80,21); mysql> insert into DemoTable634 values('Robert',70,24);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable634;
这将产生以下输出-
+-----------+-------+------+ | FirstName | Marks | Age | +-----------+-------+------+ | John | 60 | 23 | | Chris | 80 | 21 | | Robert | 70 | 24 | +-----------+-------+------+ 3 rows in set (0.00 sec)
以下是显示多列等级的查询-
mysql> SELECT FirstName,Marks,Age, FIND_IN_SET( Marks,( SELECT GROUP_CONCAT( Marks ORDER BY Marks DESC ) FROM DemoTable634)) AS RankOfMarks, FIND_IN_SET(Age,( SELECT GROUP_CONCAT( Age ORDER BY Age DESC ) FROM DemoTable634) ) AS RankOfAge FROM DemoTable634;
这将产生以下输出,显示基于标记和年龄的排名-
+-----------+-------+------+-------------+-----------+ | FirstName | Marks | Age | RankOfMarks | RankOfAge | +-----------+-------+------+-------------+-----------+ | John | 60 | 23 | 3 | 2 | | Chris | 80 | 21 | 1 | 3 | | Robert | 70 | 24 | 2 | 1 | +-----------+-------+------+-------------+-----------+ 3 rows in set (0.01 sec)