1

这是我的数据

电影表:

id title
10 Promise Land
13 Alive
14 Bruce Almighty
15 Decay
19 Malcom X

用户表:

id username
1  Franck
2  Matt

存档表:

userid movieid
1      13
2      14
1      14

我想获取所有不在用户 id = 1 的存档表中的 movies.id、movies.title。我想使用 JOINS(我不想选择 select)

结果应该是:

id title
10 Promise Land
15 Decay
19 Malcom X

以下 SQL 失败:

SELECT a.id,a.title 
FROM db.movies AS a
LEFT JOIN db.archive AS b ON a.id = b.movieid
LEFT JOIN db.users AS c ON c.id = b.userid
WHERE b.movieid IS NULL OR b.userid !=1;

谢谢

4

4 回答 4

2

使用联接。您将 userid 过滤器放入 JOIN

SELECT
    a.id,a.title 
FROM
    binews.movies AS a
    LEFT JOIN
    binews.archive AS b ON a.id = b.movieid AND b.userid <> 1
WHERE
    b.movieid IS NULL;

但是,您实际上是在问“在存档表中为该用户提供不存在的电影)

SELECT
    a.id,a.title 
FROM
    binews.movies AS a
WHERE
    NOT EXISTS (SELECT *
          FROM
             binews.archive AS b
          WHERE
             a.id = b.movieid AND b.userid <> 1);

这通常更正确。在某些情况下,您将从 LEFT JOIN 中获得多行,其中用户 ID 多次使用相同的行。要更正此问题,您需要添加处理的 DISTINCT。

但是,EXISTS 删除了这个多行输出。

有关更多信息,请参见:http: //explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/

于 2013-03-02T09:43:08.920 回答
1

在 SQLServer2005+ 中,您可以将选项与 EXISTS 和EXCEPT运算符一起使用

SELECT *
FROM dbo.movies
WHERE EXISTS (
              SELECT id
              EXCEPT
              SELECT movieid
              FROM archive
              WHERE userid = 1
              ) 

SQLFiddle上的演示

带有 NOT EXISTS AND INTERSECT运算符的OR选项

SELECT *
FROM dbo.movies
WHERE NOT EXISTS (                            
                  SELECT movieid
                  FROM archive
                  WHERE userid = 1
                  INTERSECT 
                  SELECT id
                  ) 

SQLFiddle上的演示

于 2013-03-02T10:50:55.673 回答
0
select * from binews.movies 
      where id not in(select movieid from binews.archive where userid<>1 )
于 2013-03-02T09:43:11.813 回答
0

感谢GBN。这是带有更正“AND b.userid = 1”的解决方案

SELECT
    a.id,a.title 
FROM
    binews.movies AS a
    LEFT JOIN
    binews.archive AS b ON a.id = b.movieid AND b.userid=1
WHERE
b.movieid IS NULL
于 2013-03-02T10:13:46.163 回答