我有以下架构,并且想执行一个查询,为 articles
表中的每个条目返回一行,它对应 content
列 content
表,以及包含每个文章标签的列,例如您可以使用 concat
获得的标签。
查询应该只选择与特定标记匹配的行。因此,如果提供了标签 atdi
,结果集将类似于:
id content tags
1 on my way nails broke and fell song,atdi,invalid
3 im all alone so far up here and my oxygen is all gone song,atdi,hourglass
4 you know your insides true better than i do song,atdi,starslight
我已经尝试了几种不同的子查询方法,但总是出现错误 - 这非常令人沮丧。
这是架构:
CREATE TABLE articles (
id int not null default 0,
published datetime,
author int not null default 0,
primary key (id)
);
INSERT INTO articles
(id, published, author)
VALUES
(1, CURRENT_TIMESTAMP, 1),
(2, CURRENT_TIMESTAMP, 1),
(3, CURRENT_TIMESTAMP, 1),
(4, CURRENT_TIMESTAMP, 1);
CREATE TABLE content (
id int not null default 0,
content varchar(250) not null default '',
primary key (id)
);
INSERT INTO content
(id,content)
VALUES
(1,'on my way nails broke and fell'),
(2,'exo skeleton junction at the railroad delayed'),
(3,'im all alone so far up here and my oxygen is all gone'),
(4,'you know your insides true better than i do');
CREATE TABLE tags (
id int not null default 0,
tag varchar(100) not null default '',
primary key (id,tag)
);
INSERT INTO tags
(id,tag)
VALUES
(1,"song"),
(2,"song"),
(3,"song"),
(4,"song"),
(1,"atdi"),
(2,"mars"),
(3,"atdi"),
(4,"atdi"),
(1,"invalid"),
(2,"roulette"),
(3,"hourglass"),
(4,"starslight");
最佳答案
试试这个吧
select a.id, a.content, b.tags_1
from content as a inner join (
select id, GROUP_CONCAT(tag SEPARATOR ',') as tags_1 FROM tags group by id
) as b on a.id = b.id
INNER JOIN tags AS c ON a.id = c.id
WHERE c.tag = 'atdi'
使用 GROUP_CONCAT()
方法
关于mysql - 聚合联接表导致 MySQL 5 上的 SQL SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6329156/