select music_name from( select m.user_id,m.music_id,music_name,rank() over(partition by music_name order by m.user_id) as rn from music_likes m left join (select* from follow where user_id=1) u on m.user_id=u.follower_id join music on m.music_id=music.id where u.follower_id is not null or m.user_id=1) as table1 where rn=1 and user_id!=1 order by table1.music_id
首先利用子查询我们从follow表中筛选得到关注的人的id名单然后join到music_likes表中,找到id为1的用户喜欢的歌曲以及他关注的人喜欢的歌曲。
利用rank函数和rn不为1我们可以去掉其中重复的歌曲,然后分为两种情况:1.他关注的人喜欢的歌曲里有他喜欢的歌曲,我们已经利用rn不为1顺便去除了,这是因为他的id为1并且我们的rank是按照id升序的,2.他喜欢的歌曲不在他关注的人喜欢的歌曲里,我们利用user_id!=1去除。