我想做的是检索包含两个常见列(电影和年份)的所有人:
login_id | movie | year
---------|---------------------|-----------
john | the matrix | 1999
john | star wars | 1977
bob | titanic | 1997
johnny | the matrix | 1999
tony | lord of the rings | 2001
tony | lord of the rings | 2002
tony | lord of the rings | 2003
james | star wars | 1977
robert | star trek | 1966
james | titanic | 1997
bob | star trek | 1966
...
所以,如果我有兴趣找到login_id: bob
他看过的电影,还有谁看过同样的电影预期输出:
login_id | movie | year
---------|---------------------|-----------
james | titanic | 1997
robert | star trek | 1966
...
我想尽可能有效地做到这一点,如果我需要重组表格,我会这样做。第一个猜测:
SELECT login_id, movie, year, count(*)
FROM watchers
GROUP BY login_id, movie, year
HAVING count(*) > 1 **and login_id = 'bob'**
'''是我困惑的地方,因为它是按计数分组而不是拉出所有常见数据。
答案 0 :(得分:1)
我在想exists
:
select w.*
from watchers w
where exists (select 1
from watchers w2
where w2.movie = w.movie and w2.year = w.year and w2.login_id = 'bob'
);
答案 1 :(得分:0)
我建议使用自我加入:
Select t1.*
From table t0
Join table t1 on t0.movie = t1.movie
And t0.year = t1.year
Where t0.login_id ='bob'