我有3个表:文章(id,标题,内容),标签(id,tag)和tags2all(id,iditem,idtag,module)。我想选择所有带有特定标签的文章,但在结果列表中我希望能够显示每篇文章的标签。
目前我正在使用此查询显示文章列表:
SELECT GROUP_CONCAT(t.tag SEPARATOR ', ') AS tags,a.* FROM articles AS a LEFT JOIN tags2all AS ta ON ta.iditem=a.id AND ta.module='articles' JOIN tags AS t ON ta.idtag=t.id GROUP BY a.id HAVING a.title IS NOT NULL
它似乎工作得相当好,但我似乎无法确定要添加到查询中的内容,只显示具有特定标记的文章。
如果我添加WHERE t.id = 3,它会选择正确的文章,但标记列表将只包含该标记。
答案 0 :(得分:1)
这似乎对我有用:
select a.*
from
(
SELECT GROUP_CONCAT(t.tag SEPARATOR ', ') AS tags,a.id,a.title,a.content
FROM articles AS a LEFT JOIN tags2all AS ta ON ta.iditem=a.id
AND ta.module='articles' JOIN tags AS t ON ta.idtag=t.id
GROUP BY a.id HAVING a.title IS NOT NULL
) a inner join tags2all t2a on t2a.iditem = a.id
inner join tags t on t.id = t2a.idtag
where t.id = 3;
这是我使用的DDL和数据:
create table articles (id int unsigned not null primary key, title varchar(50), content varchar(50));
create table tags (id int unsigned not null primary key, tag varchar(50));
create table tags2all (id int unsigned not null primary key, iditem int unsigned not null, idtag int unsigned not null, module varchar(50));
insert into articles values (1,"Article1","Some content");
insert into articles values (2,"Article2","Some content");
insert into articles values (3,"Article3","Some content");
insert into tags values (1,"Tag1");
insert into tags values (2,"Tag2");
insert into tags values (3,"Tag3");
insert into tags values (4,"Tag4");
insert into tags values (5,"Tag5");
insert into tags values (6,"Tag6");
insert into tags values (7,"Tag7");
insert into tags2all (id,iditem,idtag,module) values (1,1,1,"articles");
insert into tags2all (id,iditem,idtag,module) values (2,1,2,"articles");
insert into tags2all (id,iditem,idtag,module) values (3,1,3,"articles");
insert into tags2all (id,iditem,idtag,module) values (4,2,3,"articles");
insert into tags2all (id,iditem,idtag,module) values (5,2,4,"articles");
insert into tags2all (id,iditem,idtag,module) values (6,2,5,"articles");
insert into tags2all (id,iditem,idtag,module) values (7,3,3,"articles");
insert into tags2all (id,iditem,idtag,module) values (8,3,4,"articles");
insert into tags2all (id,iditem,idtag,module) values (9,3,7,"articles");
答案 1 :(得分:0)
我不确定但是试试吧
SELECT GROUP_CONCAT(t.tag SEPARATOR ', ') AS tags,a.* FROM articles AS a
LEFT JOIN tags2all AS ta ON ta.iditem=a.id AND ta.module='articles'
JOIN tags AS t ON ta.idtag=t.id
JOIN tags AS t1 ON ta1.idtag=t.id
GROUP BY a.id HAVING a.title IS NOT NULL