我正在构建一个非常简单的 cms。
其中的两个对象是文章和标签
这是我目前拥有的数据库模式:
使用它,我可以按标签获取文章列表SELECT ... WHERE web_tag.Name = 'News'
问题
如何获取不包含标签的文章列表。
我试着做
SELECT ... WHERE web_tag.Name != 'News'
如果文章只有一个标签,则此方法有效。如果文章明显有多个标签,它将不起作用
非常感谢!
一种方法
SELECT a.id_article, a.name
FROM web_article a
WHERE NOT EXISTS
(
SELECT *
FROM web_tag_to_article ta JOIN web_tag t
ON ta.id_tag = t.id_tag
WHERE id_article = a.id_article
AND t.name = 'News'
)
或者
SELECT id_article, name
FROM web_article
WHERE id_article NOT IN
(
SELECT id_article
FROM web_tag_to_article ta JOIN web_tag t
ON ta.id_tag = t.id_tag
GROUP BY id_article
HAVING MAX(t.name = 'News') = 1
)
或者
SELECT a.id_article, a.name
FROM web_article a LEFT JOIN web_tag_to_article ta
ON a.id_article = ta.id_article LEFT JOIN web_tag t
ON ta.id_tag = t.id_tag
GROUP BY a.id_article, a.name
HAVING MAX(COALESCE(t.name,'') = 'News') = 0
这是SQLFiddle演示
另一种方式
select ID_Articles, Name, Slug from web_article where ID_Article in (select ID_Articles from web_article except (select ID_Article from web_tag_to_Article where ID_Tag in (select ID_Tag from web_tag where name='news'))