gpt4 book ai didi

mysql - 如何使用一个 MySQL 查询选择所有带有标签的文章和所有文章的标签?

转载 作者:行者123 更新时间:2023-11-29 00:50:51 25 4
gpt4 key购买 nike

我有 3 个表:文章(id、标题、内容)、标签(id、标签)和 tags2all(id、iditem、idtag、模块)。我想选择带有特定标签的所有文章,但在结果列表中我还希望能够显示每篇文章的标签。

目前我正在使用这个查询来显示文章列表:

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,它会选择正确的文章,但标签列表将只包含该标签。

最佳答案

这对我来说似乎工作正常:

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");

关于mysql - 如何使用一个 MySQL 查询选择所有带有标签的文章和所有文章的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8613451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com