我正在构建一个非常简单的cms。
其中的两个对象是文章和标签
这是我目前的数据库模式:
使用此功能,我可以按标签SELECT ... WHERE web_tag.Name = 'News'
如何获得 DONOT 包含标签的文章列表。
我试着做了
SELECT ... WHERE web_tag.Name != 'News'
如果文章只有一个标签,这项工作。如果文章明显有多个标签,那么它将不起作用
非常感谢!
答案 0 :(得分:1)
一种方法
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 演示
答案 1 :(得分:0)
另一种方式
从web_article中选择ID_Articles,Name,Slug,其中ID_Article在 (从web_article中选择ID_Articles除外 (从web_tag_to_Article中选择ID_Article,其中ID_Tag位于 (从web_tag中选择ID_Tag,其中name ='news')))