--- 最直观的理解
- user_id=1 的用户所关注的所有follower的id
(SELECT DISTINCT(follower_id)
FROM follow
WHERE user_id = 1)
- user_id=1 的用户所关注的所有follower喜欢的所有音乐的id
(SELECT music_id
FROM music_likes
WHERE user_id IN (SELECT DISTINCT(follower_id)
FROM follow
WHERE user_id = 1))
- user_id=1 的用户所喜欢的所有音乐的id
(SELECT music_id
FROM music_likes
WHERE user_id = 1)
-
完整代码
给user_id=1 的用户推荐音乐,等价于:
-
确保音乐的id IN (所有follower所喜欢的音乐id);
-
确保音乐的id NOT IN (user_id=1 的用户所喜欢的音乐id),因此有:
SELECT DISTINCT(music_name)
FROM music
WHERE id IN (SELECT music_id
FROM music_likes
WHERE user_id IN (SELECT DISTINCT(follower_id)
FROM follow
WHERE user_id = 1))
AND id NOT IN (SELECT music_id
FROM music_likes
WHERE user_id = 1)
ORDER BY id
;