本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL常用函数大汇总》、《MySQL日志 *** 作技巧大全》、《MySQL事务 *** 作技巧汇总》、《MySQL存储过程技巧大全》及《MySQL数据库锁相关技巧汇总》
希望本文所述对大家MySQL数据库计有所帮助。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)