题解 | #网易云音乐推荐(网易校招笔试真题)#
网易云音乐推荐(网易校招笔试真题)
http://www.nowcoder.com/practice/048ed413ac0e4cf4a774b906fc87e0e7
方法一(笨办法,一层一层嵌套,有点常规思路比较好理解和想到)
问题拆解:1.表1follow中提取字段follow_id,设定筛选条件user_id=1,找出用户id为1的关注了哪些用户;
(SELECT follower_id FROM follow WHERE user_id =1)
2.从表格music_likes中选择music_id,设定筛选条件user_id是在步骤1的序列中,
3.同时music_id也不能是自己已经喜欢的音乐,步骤2的筛选条件同时加上music_id不在user_id=1的序列中
4.对步骤3music_id去重
5.将步骤4新生成的表格r1和最后表music链接,提取music的name
6.常规orderby
完结,撒花~~
SELECT music_name FROM
(SELECT DISTINCT music_id FROM music_likes
WHERE user_id IN
(SELECT follower_id FROM follow WHERE user_id =1)
AND music_id NOT IN
(SELECT music_id FROM music_likes
WHERE user_id =1)) r1
JOIN music m
ON r1.music_id=m.id
ORDER BY m.id
方法二(少生成几个新表格,少嵌套一点,格式比较清晰)
方法二问题拆解:1.根据题目要求设定筛选条件表1.user_id=1
2.筛选条件2 表1的follower_id=表2的user_id
3.筛选条件3 表2的music_id=表3的id
4.筛选条件4 表3的id中不能包含user_id本身为1的music_id
5.最后orderby即可
SELECT distinct music_name FROM
follow f, music_likes ml, music m
WHERE f.user_id=1
AND f.follower_id=ml.user_id
AND ml.music_id=m.id
AND m.id NOT IN
(SELECT music_id FROM music_likes WHERE user_id=1)
ORDER BY m.id