【发布时间】:2020-01-17 17:34:32
【问题描述】:
我正在使用 sqlite3 并尝试选择具有任何(或全部)给定标签的所有文章。
CREATE TABLE article (
id INTEGER NOT NULL,
title TEXT NOT NULL,
PRIMARY KEY (id),
UNIQUE (title)
);
CREATE TABLE tag (
id INTEGER NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (id),
UNIQUE (name)
);
CREATE TABLE drill_to_tag (
tag_id INTEGER NOT NULL,
article_id INTEGER NOT NULL,
PRIMARY KEY (tag_id, article_id),
FOREIGN KEY(tag_id) REFERENCES tag (id),
FOREIGN KEY(article_id) REFERENCES article (id)
);
假设标签 id 4 是“新闻”,标签 id 5 是“欧洲”,标签 id 6 是“美国”。
我可以使用以下方法获取标签 id 为 4 的文章:
select a.title from article a
inner join article_to_tag
on a.id = article_to_tag.article_id
where article_to_tag.tag_id = 4;
但我真正想要的是一种让文章出现在多对多表中的方法, 标签 4 和 5 -- 欧洲新闻。
这个查询可以做到,但看起来很难看?
select a.id, a.title from article a
inner join article_to_tag atag1
on a.id = atag1.article_id
inner join article_to_tag atag2
on a.id = atag2.article_id
where atag1.tag_id = 4 and atag2.tag_id = 5;
而且这个看起来更丑。
select a.id, a.title from article a
where
a.id in (select article_id from article_to_tag where article_id = 4)
and
a.id in (select article_id from article_to_tag where article_id = 5);
有没有更好的连接类型或其他方式来形成这个查询?
【问题讨论】:
标签: sql sqlite join many-to-many