题38:
根据下面两个表编写一个SQL查询来查找针对每个用户的所有可能的页面建议。每个建议应该在结果表中显示为一行,包含以下列:
- user_id:系统向其提出建议的用户的ID;
- page_id: 推荐为user_id的页面ID;
- friends_likes: user_id对应page_id的好友数。
注意:如果页面被user_id的至少一个朋友喜欢,而不被user_id喜欢,系统将推荐一个页面到user_id。
其中:
- user1_id,user2_id是Friendship表的主键,该表的每一行表示用户user1_id和user2_id是好友;
- user_id,page_id是Likes表的主键,该表的每一行表示user_id喜欢page_id。
解题思路:
(1)union all 拼接用户列及其对应好友为表f
select user1_id,user2_id
from Friendship
union all
select user2_id,user1_id
from Friendship
(2)f表和Likes表左连接,连接条件:user2_id=user_id;
(3)筛选出用户和好友喜欢的相同页面
代码如下:
select f.user1_id as user_id,l.page_id,count(*) as friends_likes
from(
select user1_id,user2_id
from Friendship
union all
select user2_id,user1_id
from Friendship
) f
left join Likes as l
on user2_id=user_id
where not exists (
select *
from Likes
where user_id=user1_id
and page_id=l.page_id
)--not exsist 的写法是 where not exsist(select x,y from table where x=x,y=y)
group by user1_id,page_id;