1892.(Hard)Page Recommendations II

Table: Friendship

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user1_id      | int     |
| user2_id      | int     |
+---------------+---------+
(user1_id,user2_id)是Friendship表的主键。
该表的每一行表示用户user1_id和user2_id是好友。

Table: Likes

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| page_id     | int     |
+-------------+---------+
(user_id,page_id)是Likes表的主键。
(user_id, page_id) is the primary key for this table.
该表的每一行表示user_id喜欢page_id。

您正在为一个社交媒体网站实施一个页面推荐系统。如果页面被user_id的至少一个朋友喜欢,而不被user_id喜欢,你的系统将推荐一个页面到user_id。

编写一个SQL查询来查找针对每个用户的所有可能的页面建议。每个建议应该在结果表中显示为一行,包含以下列:

user_id: 系统向其提出建议的用户的ID。 page_id: 推荐为user_id的页面ID。. friends_likes: user_id对应page_id的好友数。 以任意顺序返回结果表。

查询结果格式示例如下:

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/page-recommendations-ii

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution

用 not in 排除“自己已喜欢的页面” 可以做出来,但是效率较低,超出时间限制了。

正确做法:

  • 两次 LEFT JOIN Likes ,分别匹配出“朋友喜欢”和“我喜欢”,注意先后顺序。

  • 配合 where l1.page_id is null 剔除掉同时喜欢的页面。

Schema

Last updated

Was this helpful?