题目
请写一段SQL查询获取到兴趣相同的朋友。用户 x
和 用户 y
是兴趣相同的朋友,需满足下述条件:
- 用户
x
和y
是朋友,并且 - 用户
x
andy
在同一天内听过相同的歌曲,且数量大于等于三首.
结果表 无需排序 。注意:返回的结果需要和源数据表的呈现方式相同 (例如, 需满足 user1_id < user2_id
)。
准备数据
Create table If Not Exists Listens (user_id int, song_id int, day date)
Create table If Not Exists Friendship (user1_id int, user2_id int)Truncate table Listensinsert into Listens (user_id, song_id, day) values ('1', '10', '2021-03-15')insert into Listens (user_id, song_id, day) values ('1', '11', '2021-03-15')insert into Listens (user_id, song_id, day) values ('1', '12', '2021-03-15')insert into Listens (user_id, song_id, day) values ('2', '10', '2021-03-15')insert into Listens (user_id, song_id, day) values ('2', '11', '2021-03-15')insert into Listens (user_id, song_id, day) values ('2', '12', '2021-03-15')insert into Listens (user_id, song_id, day) values ('3', '10', '2021-03-15')insert into Listens (user_id, song_id, day) values ('3', '11', '2021-03-15')insert into Listens (user_id, song_id, day) values ('3', '12', '2021-03-15')insert into Listens (user_id, song_id, day) values ('4', '10', '2021-03-15')insert into Listens (user_id, song_id, day) values ('4', '11', '2021-03-15')insert into Listens (user_id, song_id, day) values ('4', '13', '2021-03-15')insert into Listens (user_id, song_id, day) values ('5', '10', '2021-03-16')insert into Listens (user_id, song_id, day) values ('5', '11', '2021-03-16')insert into Listens (user_id, song_id, day) values ('5', '12', '2021-03-16')Truncate table Friendshipinsert into Friendship (user1_id, user2_id) values ('1', '2')insert into Friendship (user1_id, user2_id) values ('2', '4')insert into Friendship (user1_id, user2_id) values ('2', '5')
listens表
friendship表
分析数据
select distinct user1_id,user2_id
from Friendship fleft join Listens l1on user1_id=l1.user_idleft join Listens l2on user2_id=l2.user_id
where l1.song_id=l2.song_idand l1.day=l2.day
group by user1_id,user2_id,l1.day
having count(distinct l2.song_id)>=3;
总结
这道题是找出在friendship表存在的,只需要关联就行.与1917题不同.