MySQL左外部联接和组合结果
作者:互联网
我正在努力加入.基本上,我希望查询的标记结果在一行中.
以下是我的表格:
>封面
>类别
> Cover_tag
>标签
该查询返回封面,类别以及该类别的所有标签.允许在标签中使用NULL结果,因此无论是否未添加标签,我都可以获取所有封面.
在数据库中,我在封面中有2行.第一封面没有标签,第二封面没有标签.当运行下面的查询时,我得到4行.其中3个是第一个封面,带有不同的标签,第4个是没有标签的行.
我基本上希望2个结果在一行中包含每个封面的所有标签.这可能吗?
SELECT *
FROM cover
JOIN category ON cover.category_id = category.id
LEFT OUTER JOIN cover_tag ON cover_tag.cover_id = cover.id
LEFT OUTER JOIN tag ON cover_tag.tag_id = tag.id
来自phpMyAdmin的数据
CREATE TABLE `category` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `category` VALUES(1, 'Cars', 'cars');
INSERT INTO `category` VALUES(2, 'Music', 'music');
INSERT INTO `category` VALUES(3, 'Abstract', 'abstract');
CREATE TABLE `cover` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`category_id` int(9) NOT NULL,
`title` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `cover` VALUES(1, 1, 'Red Ferarri', 'red-ferarri', 'redferrari.jpg', '2011-12-20 23:48:11');
INSERT INTO `cover` VALUES(2, 1, 'Ford Focus ST', 'ford-focus-st', 'focuss.jpg', '2011-12-20 23:48:11');
CREATE TABLE `cover_tag` (
`cover_id` int(9) NOT NULL,
`tag_id` int(9) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `cover_tag` VALUES(1, 1);
INSERT INTO `cover_tag` VALUES(1, 2);
INSERT INTO `cover_tag` VALUES(1, 3);
CREATE TABLE `tag` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`tag` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `tag` VALUES(1, 'cars');
INSERT INTO `tag` VALUES(2, 'ferarri');
INSERT INTO `tag` VALUES(3, 'speed');
解决方法:
您可以使用group by将它们与GROUP_CONCAT
连接起来,如下所示:
Select c.title, GROUP_CONCAT(t.tag SEPARATOR ', ')
From cover c
Join cCategory ct on c.Category_Id = ct.id
LEFT OUTER JOIN cover_tag ctg ON c.Id = ctg.cover_id
LEFT OUTER JOIN tag t on ctg.tag_id = t.id
GROUP By c.title
这将为您提供以下内容:
title Tags
------------------------------------
Ford Focus ST {NULL}
Red Ferarri cars, ferarri, speed
标签:group-concat,sql,mysql 来源: https://codeday.me/bug/20191101/1986920.html