2

我有一个关于 sql 查询的简单逻辑问题。

一些文章有一个历史记录表,并且文章有一个带有 status_id 的行。一篇文章可以有各种状态,我只想得到这些文章,它们从来没有给定的状态。例如:

articlename | status_id
article1    |  2
article1    |  1
article1    |  3
article2    |  2
article2    |  3
article3    |  2
article3    |  3


SELECT * FROM article WHERE article.status_id != 2 GROUP BY article.id

这只是我得到“article1”的错误代码,因为它有 2 行适合此语句。我认为解决方案很简单,但我现在无法得到-.-

提前致谢

4

1 回答 1

2

您需要使用NOT IN删除所有状态为“2”的文章。

/* NOT IN BASED APPROACH */
SELECT * 
FROM article 
WHERE article.id NOT IN (
    SELECT article.id 
    FROM article
    WHERE article.status_id = 2)

/* NOT EXISTS BASED APPROACH */
SELECT * 
FROM article 
WHERE article.id NOT EXISTS (
    SELECT *
    FROM article
    WHERE article.status_id = 2)

/* JOIN BASED APPROACH */
SELECT *
FROM   article a1 LEFT JOIN
       article a2 
       ON a1.id = a2.id 
       AND a2.status_id = 2
WHERE  a2.id IS NULL
于 2012-08-08T13:34:58.463 回答