MySQL的Group By分组

2014-11-24 17:21:34 · 作者: · 浏览: 0

CategoryID int


);


insert into sod_artist_category_relation values (1,1),(1,2),(1,3),(2,3),(2,4),(3,1);




假设这是歌曲和歌曲分类的映射表,一个歌曲可以有多个分类,比如"华语"和"男歌星"。
MySQL可以进行如下分组:

select songid,CategoryID,count(*) from sod_artist_category_relation group by songid;




他除了正常的分组,还可以带上其他的字段,如果这些额外的字段有重复,则选择第一个数据。

这个特性很方便,如果使用Oracle,可以使用相关子查询模拟,

select songid,

(select min(CategoryID) from sod_artist_category_relation where songid=t1.songid) CategoryID,


count(*) from sod_artist_category_relation t1 group by songid;