您好,欢迎访问一九零五行业门户网

MySQL分组排序取前N条记录 以及 生成自动数字序列 的SQL

-- mysql分组排序取前n条记录的最简洁的单条sql。
use test;
drop table if exists test;
create table test ( id int primary key, cid int, author varchar(30) ) engine=myisam;
insert into test values (1,1,'test1'), (2,1,'test1'), (3,1,'test2'), (4,1,'test2'), (5,1,'test2'), (6,1,'test3'), (7,1,'test3'), (8,1,'test3'), (9,1,'test3'), (10,2,'test11'), (11,2,'test11'), (12,2,'test22'), (13,2,'test22'), (14,2,'test22'), (15,2,'test33'), (16,2,'test33'), (17,2,'test33'), (18,2,'test33');
insert into test values (200,200,'200test_nagios');
select * from (select cid,author,count(*) as number from test group by cid,author) a where n >( select count(*) from (select cid,author,count(*) as number from test group by cid,author) b where a.cid=b.cid and a.number<b.number )order by cid,number desc;
结果如下:
mysql> select * from (select cid,author,count(*) as number from test group by cid,author) a -> where -> 3>( -> select count(*) -> from (select cid,author,count(*) as number from test group by cid,author) b -> where a.cid=b.cid and a.number<b.number -> )order by cid,number desc; +------+----------------+--------+ | cid | author | number | +------+----------------+--------+ | 1 | test3 | 4 | | 1 | test2 | 3 | | 1 | test1 | 2 | | 2 | test33 | 4 | | 2 | test22 | 3 | | 2 | test11 | 2 | | 200 | 200test_nagios | 1 | +------+----------------+--------+ 7 rows in set (0.00 sec)
n就是取分组之后的最前面几个判断,n=3就是取前3个
-- 生成自动数字序列
set @row=0; select a.*,(@row:=@row +1)rank from test a;
以上就是mysql分组排序取前n条记录 以及 生成自动数字序列 的sql的内容。
其它类似信息

推荐信息