在mysql使用中,经常需要查询每个分组的前几条记录(查询分组后每一个组的前几项),下面写了个简单的例子说明下sql的写法。简单的表设计如下,要求每个班总分排名最前的前两条数据。 测试表语句如下: create table test(id int unsigned not null auto_inc
在mysql使用中,经常需要查询每个分组的前几条记录(查询分组后每一个组的前几项),下面写了个简单的例子说明下sql的写法。简单的表设计如下,要求每个班总分排名最前的前两条数据。
测试表语句如下:
create table test(id int unsigned not null auto_increment primary key,name varchar(10),class varchar(20),score varchar(20));insert into test(name, class, score) values ('gonn', '6(1)', '299');insert into test(name, class, score) values ('yyun', '6(1)', '259');insert into test(name, class, score) values ('lin', '6(1)', '289');insert into test(name, class, score) values ('mei', '6(1)', '277');insert into test(name, class, score) values ('xj', '6(2)', '287');insert into test(name, class, score) values ('zhl', '6(2)', '277');insert into test(name, class, score) values ('lwjs', '6(2)', '257');insert into test(name, class, score) values ('lulu', '6(2)', '265');
运行以上sql,得到的表结构如下:
mysql> select * from test;+----+------+-------+-------+| id | name | class | score |+----+------+-------+-------+| 1 | gonn | 6(1) | 299 || 2 | yyun | 6(1) | 259 || 3 | lin | 6(1) | 289 || 4 | mei | 6(1) | 277 || 5 | xj | 6(2) | 287 || 6 | zhl | 6(2) | 277 || 7 | lwjs | 6(2) | 257 || 8 | lulu | 6(2) | 265 |+----+------+-------+-------+8 rows in set
方法一mysql> select a.id,a.name,a.class,a.scorefrom test a left join test b on a.class = b.class and a.score (select count(*) from test where class = a.class and score>a.score)order by a.class,a.score desc;+----+------+-------+-------+| id | name | class | score |+----+------+-------+-------+| 1 | gonn | 6(1) | 299 || 3 | lin | 6(1) | 289 || 5 | xj | 6(2) | 287 || 6 | zhl | 6(2) | 277 |+----+------+-------+-------+4 rows in set
这里列出了多种sql语句的实现方法,有些是mysql特有的(limit, 其它数据库可根据实际更改,比如oracle的rownum,ms sql server 的 top,..),有时是sql标准支持的。但效率上和应用的场合或许不同。具体应用时可根据实际表中的记录情况,索引情况进行选择。