MySQL-取某個欄位表中每組幾行資料方式

markzy5201190發表於2013-05-18
MySQL-取某個欄位表中每組幾行資料

因開發要求,對某張有多組資料表,對其每個組中取前幾行資料sql:
形式如下:
create table tbl(
Id int(11) not null auto_increment,
type int(11) not null,
name char(1) not null,
primary key(Id),
key idx_type(type)
)engine=InnoDB default charset=utf8;

insert into tbl(type,name)values(1,'aa');
insert into tbl(type,name)values(1,'ab');
insert into tbl(type,name)values(1,'ac');
insert into tbl(type,name)values(2,'ad');
insert into tbl(type,name)values(2,'ac');
insert into tbl(type,name)values(2,'ae');
insert into tbl(type,name)values(3,'ax');
insert into tbl(type,name)values(4,'ag');
insert into tbl(type,name)values(3,'ad');
.....

sql如下:
如每組資料的前2行,若有其他方法,煩請各位分享..
select a.*
from tbl a
where 2>(select count(0) from tbl b where a.type=b.type and a.Id>b.Id);


end---

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26855487/viewspace-761427/,如需轉載,請註明出處,否則將追究法律責任。

相關文章