服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|

服务器之家 - 数据库 - Mysql - mysql中GROUP_CONCAT的使用方法实例分析

mysql中GROUP_CONCAT的使用方法实例分析

2021-01-07 16:47怀素真 Mysql

这篇文章主要介绍了mysql中GROUP_CONCAT的使用方法,结合实例形式分析了MySQL中GROUP_CONCAT合并查询结果的相关操作技巧,需要的朋友可以参考下

本文实例讲述了mysql中group_concat的使用方法。分享给大家供大家参考,具体如下:

现在有三个表,结构如下:

cate表:

?
1
2
3
4
5
create table `cate` (
 `id` int(10) unsigned not null auto_increment comment 'id',
 `name` char(20) default '' comment '分类名',
 primary key (`id`)
) engine=innodb auto_increment=5 default charset=utf8 comment='文章分类表';

article表:

?
1
2
3
4
5
6
create table `article` (
 `id` int(10) unsigned not null auto_increment comment 'id',
 `title` varchar(50) default '',
 `cate_id` int(11) not null default '0' comment '分类id',
 primary key (`id`)
) engine=innodb auto_increment=5 default charset=utf8 comment='文章表';

article_extend表:

?
1
2
3
4
5
6
create table `article_extend` (
 `id` int(10) unsigned not null auto_increment,
 `article_id` int(10) unsigned default '0' comment '文章id',
 `name` varchar(255) default '' comment '音频,图片之类',
 primary key (`id`)
) engine=innodb auto_increment=4 default charset=utf8 comment='附件表';

三张表数据如下:

cate表:

mysql中GROUP_CONCAT的使用方法实例分析

article表:

mysql中GROUP_CONCAT的使用方法实例分析

article_extend表:

mysql中GROUP_CONCAT的使用方法实例分析

问题来了,现在通过表连接查询,查询文章id为1的文章数据,并显示文章标题,文章分类,文章name。

?
1
2
3
4
5
6
7
8
9
10
11
select
    a.id as aid,
    a.title as atitle,
    c. name as cname,
    ae. name as aname
from
    article as a
left join cate as c on a.cate_id = c.id
left join article_extend as ae on a.id = ae.article_id
where
    a.id = 1;

结果如下,出现了两条数据:

mysql中GROUP_CONCAT的使用方法实例分析

现在只想要一条结果,aname字段进行合并,如何做?

只有通过group_concat来实现了:

?
1
2
3
4
5
6
7
8
9
10
11
select
    a.id as aid,
    a.title as atitle,
    c. name as cname,
    group_concat(ae. name separator '-') as aname
from
    article as a
left join cate as c on a.cate_id = c.id
left join article_extend as ae on a.id = ae.article_id
where
    a.id = 1;

结果如下:

mysql中GROUP_CONCAT的使用方法实例分析

那么,现在我们不想通过文章id一条一条的查,我们要取全部,但如果文章name有多个的要进行合并,如何做?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
select
    a.id as aid,
    a.title as atitle,
    c. name as cname,
    ae.allname
from
    article as a
left join (
    select
        ae.article_id,
        group_concat(ae. name) as allname
    from
        article_extend as ae
    group by
        ae.article_id
) as ae on a.id = ae.article_id
left join cate as c on a.cate_id = c.id;

结果如下:

mysql中GROUP_CONCAT的使用方法实例分析

希望本文所述对大家MySQL数据库计有所帮助。

原文链接:https://www.cnblogs.com/jkko123/p/6294718.html

延伸 · 阅读

精彩推荐