我有一张表投票表示我是否有用户投票支持特定电影。它还显示了用户投票的电影数量。
id_film | id_user | voting
----------------------------
1 | 1 | 7
1 | 33 | 5
3 | 1 | 9
4 | 7 | 7
4 | 2 | 8
4 | 1 | 6
6 | 1 | 6
... | ... | ...
我希望以这种方式获取与id_user相关的id_film列表:
从特定的id_user获取 id_film&#39>
SELECT id_film FROM投票WHERE id_user = 1
抓住每个相关的id_user
SELECT DISTINCT v.user FROM vote v WHERE id_film IN( id_film' s )
然后选择 id_film&#39; FROM投票v WHERE用户IN(&#34;来自先前查询的用户列表&#34;),除了 id_film&#39; s < / strong>来自第一次查询。
这是我的第一次尝试:
SELECT id_film, film.title, film.originaltitle, COUNT(*)
FROM votes v
INNER JOIN film ON v.id_film = film.id
WHERE user IN
(
SELECT DISTINCT v.user
FROM votes v
WHERE id_film IN
(
SELECT id_film
FROM votes v
WHERE user = 1
)
)
AND
id_film NOT IN
(
SELECT id_film
FROM votes v
WHERE user = 1
)
GROUP BY id_film
它不起作用。 MySQL花了太长时间才得到结果,我重启了XAMPP。
所以我尝试了另一个SELECT,这次使用 JOINS :
SELECT DISTINCT v.id_film AS vFilm, v1.user AS v1User, v2.id_film AS v2Film
FROM votes v
LEFT OUTER JOIN votes v1 ON v1.id_film = v.id_film
LEFT OUTER JOIN votes v2 ON v1.user = v2.user
WHERE v.user = 1
AND v1.user != 1
AND v2.id_film NOT
IN
(
SELECT id_film
FROM votes
WHERE user = 1
)
GROUP BY v2.id_film
同样不起作用,但是当我在没有 NOT IN 条件的情况下尝试它时,它的确有效! (花了大约13秒。): - (
这是工作查询。
SELECT DISTINCT v2.id_film AS v2Film
FROM votes v
LEFT OUTER JOIN votes v1 ON v1.id_film = v.id_film
LEFT OUTER JOIN votes v2 ON v1.user = v2.user
WHERE v.user = 1
AND v1.user != 1
带输出
v2Film
---------
1
13
14
58
4
...
但是此查询除了第一次查询的 id_film&#39>之外没有其他信息。 因为我知道用户1已经投票支持id_film 1。
那么,我的逻辑是完全错误还是我的代码太复杂了?