MySQL查询选择三个最高值,并根据名称对应的列按字母顺序排序
为此,您可以使用ORDERBY子句。让我们首先创建一个表-
mysql> create table DemoTable ( Name varchar(40), Score int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris',45); mysql> insert into DemoTable values('Bob',98); mysql> insert into DemoTable values('David',78); mysql> insert into DemoTable values('Mike',96); mysql> insert into DemoTable values('Carol',43);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 45 | | Bob | 98 | | David | 78 | | Mike | 96 | | Carol | 43 | +-------+-------+ 5 rows in set (0.00 sec)
以下是从“得分”列中选择三个最高值并按字母顺序对相应的“名称”列进行排序的查询-
mysql> select *from (select Name,Score from DemoTable order by Score desc,Name asc limit 3) tbl order by Name;
这将产生以下输出-
+-------+-------+ | Name | Score | +-------+-------+ | Bob | 98 | | David | 78 | | Mike | 96 | +-------+-------+ 3 rows in set (0.03 sec)