所以我进入了这个子查询
SELECT movies.movieID, movies.user
FROM movies
WHERE movies.user IN(Select movies.user
FROM movies
WHERE movies.movieID = '19')
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19')
AND movies.movieID <> '19'
它给了我这个结果
--------------------------
| movieID | user |
--------------------------
| 20 | 4 |
--------------------------
| 21 | 4 |
--------------------------
| 22 | 5 |
--------------------------
| 23 | 4 |
--------------------------
如何摆脱用户5的任何结果?
我认为问题出在
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19')
但是当我尝试单独运行查询时
SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19'
它只给出了2个结果,只有19,不返回movieID 22。此查询的结果是正确的。为什么在子查询中运行它时会返回22?
是的,有人可以帮帮我吗?感谢答案 0 :(得分:2)
如果您不想使用user = 5的记录,则只需添加
AND movies.user <> '5'
您的子查询
SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19'
说,选择movieID为19且用户为5的movieID。此查询将返回19.
所以这个
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19')
说我不想要movieID = 19,这就是为什么在你的最终查询中你仍然可以得到movieID = 5的记录。
答案 1 :(得分:1)
使用user ='5'过滤掉记录的子句只过滤掉user ='5'和movieID ='19'的记录
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19')
这意味着它没有过滤掉user ='5'和movieID = '22'的记录
根据您的需要,您可以尝试:
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
OR movies.movieID = '19')
或只在主AND user != 5
子句
WHERE
SELECT movies.movieID, movies.user
FROM movies
WHERE movies.user IN(Select movies.user
FROM movies
WHERE movies.movieID = '19')
AND movies.movieID <> (SELECT movies.movieID
FROM movies
WHERE movies.user='5'
AND movies.movieID = '19')
AND movies.movieID <> '19'
AND user <> '5'