这就是我认为您正在寻找的内容:
给定用户 John,找到所有电影 B,使得存在电影 A、用户 Simon 和类型 G,其中:
- 约翰将电影评为 A a 5
- 西蒙将电影评为 A a 5
- 西蒙不是约翰
- 西蒙将电影评为 B a 5
- 电影 A 属于类型 G
- 电影 B 属于 G 类型
用这种方式表达,我认为很容易提出一个查询:
select B.*
from user John
join rating JohnA on JohnA.userid = John.id and JohnA.value = 5
join movie A on A.id = JohnA.movieid
join rating ASimon on ASimon.movieid = A.id and ASimon.value = 5
join user Simon on Simon.id = ASimon.userid and Simon.id <> John.id
join rating SimonB on SimonB.userid = Simon.id and SimonB.value =5
join movie B on B.id = SimonB.movieid
join movie_genre Agenre on Agrenre.movieID = A.id
join genre G on G.id = Agenre.genreid
join movie_genre Bgenre on Bgenre.genreid = G.id and Bgenre.movieid = B.id
您选择的数据库可能会对此进行优化以删除一些连接,但我们只需要关系(评级)而不是中间对象(电影 A、用户西蒙和流派 G):
select B.*
from user John
join rating JohnA on JohnA.userid = John.id and JohnA.value = 5
join rating ASimon on ASimon.movieid = JohnA.movieid and ASimon.value = 5 and ASimon.userid <> John.id
join rating SimonB on SimonB.userid = ASimon.userid and SimonB.value =5
join movie B on B.id = SimonB.movieid
join movie_genre Agenre on Agrenre.movieID = A.id
join movie_genre Bgenre on Bgenre.genreid = Agenre.genreid and Bgenre.movieid = B.id