select
    music_name
from
    (
        select
            distinct music.music_name,music.id
        from
            follow
            inner join music_likes on follow.follower_id = music_likes.user_id
            inner join music on music.id = music_likes.music_id
        where
            follow.user_id = 1
        order by
            music.id
    ) as level1
where
    music_name not in (
        select
            music.music_name
        from
            follow
            inner join music_likes on follow.user_id = music_likes.user_id
            inner join music on music.id = music_likes.music_id
        where
            follow.user_id = 1
    )

这道题真是有意思,头一回遇见DISTINCT与order by冲突的地方:DISTINCT 会对查询结果去重,而 ORDER BY 引用了未在 SELECT 列表中出现的列(如 music.id

  • MySQL 的严格模式要求:使用 DISTINCT 时,ORDER BY 的所有列必须在 SELECT 列表中显式存在,否则会因逻辑歧义报错 。
  • 我是直接在子查询中DISTINCT直接去重,select name与id两个变量就行了,多一个这里也并不影响。

    总的思路是,使用子查询找到user_id=1对应的follower的喜欢的歌曲并排序和去重,再在最高级查询的where里使用另一个子查询筛选出除去user_id=1已经喜欢的歌曲,然后输出music_name即可。