【发布时间】:2015-10-26 09:41:55
【问题描述】:
这是我的表格和示例数据。
CREATE TABLE `articles`
(
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tags`
(
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `article_tags`
(
`article_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL
);
INSERT INTO `tags` (`id`, `name`) VALUES
(1, 'Wap Stories'),
(2, 'App Stories');
INSERT INTO `articles` (`id`, `title`) VALUES
(1, 'USA'),
(2, 'England'),
(3, 'Germany'),
(4, 'India'),
(5, 'France'),
(6, 'Dubai'),
(7, 'Poland'),
(8, 'Japan'),
(9, 'China'),
(10, 'Australia');
INSERT INTO `article_tags` (`article_id`, `tag_id`) VALUES
(1, 1),
(1, 2),
(4, 1),
(5, 1),
(2, 2),
(2, 1),
(6, 2),
(7, 2),
(8, 1),
(9, 1),
(3, 2),
(9, 2),
(10, 2);
如何获得我尝试使用 group_concat 函数的以下输出。它给出了所有的结果。但我的要求是我需要将值分组为
一个。 1,2的组合可以有,只有1可以有,2单独不能有。
b。 2,1的组合可以有,只有2可以有,1单独不能有
下面是我需要的输出
id, title, groupconcat
--------------------------
1, USA, 1,2
2, England, 1,2
4, India, 1
5, France, 1
8, Japan, 1
9, China, 1,2
我使用的查询是
select id, title, group_concat(tag_id order by tag_id) as 'groupconcat' from articles a
left join article_tags att on a.id = att.article_id
where att.tag_id in (1,2)
group by article_id order by id
【问题讨论】:
-
我不明白你的要求。请详细说明。
-
我需要获取标签所在国家/地区的标签ID。在上面的输出中您可以看到美国、英国属于标签ID 1和2,它们存储在标签表中。所以基本上我需要所有被标记为标记 id 1 的国家,如果它们被标记为标记 id 1,那么我还需要检查它们是否被标记为标记 id 2
标签: mysql group-concat