mysql中GROUP_CONCAT的使用

前端之家收集整理的这篇文章主要介绍了mysql中GROUP_CONCAT的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
现在有三个表,结构如下:
cate表
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表
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表
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表:

 article表:

 article_extend表:

问题来了,现在通过表连接查询查询文章id为1的文章数据,并显示文章标题文章分类文章name。
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;
结果如下,出现了两条数据:

现在只想要一条结果,aname字段进行合并,如何做?
只有通过GROUP_CONCAT来实现了:
SELECT
	a.id AS aid,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;
结果如下:

那么,现在我们不想通过文章id一条一条的查,我们要取全部,但如果文章name有多个的要进行合并,如何做?
SELECT
	a.id AS aid,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相关文章