这篇文章将为大家详细讲解有关怎么在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,
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;
结果如下:
那么,现在我们不想通过文章id一条一条的查,我们要取全部,但如果文章name有多个的要进行合并,如何做?
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方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。