Home > Database > Mysql Tutorial > body text

MySQL的Group By分组_MySQL

WBOY
Release: 2016-06-01 13:13:15
Original
881 people have browsed it

一直以来,还是Oracle用的比较多。
 MySQL的分组,看着总是有些奇怪。
 实验如下,创建初始化数据:
 
create table sod_artist_category_relation(
 
    songid int ,

    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;

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!