现在有三个表,结构如下:
结果如下,出现了两条数据:
结果如下:
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;