leetcode-SQL-

简介: leetcode-SQL-

题目

题目链接

朋友关系列表: Friendship

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user1_id      | int     |
| user2_id      | int     |
+---------------+---------+
这张表的主键是 (user1_id, user2_id)。
这张表的每一行代表着 user1_id 和 user2_id 之间存在着朋友关系。

喜欢列表: Likes

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| page_id     | int     |
+-------------+---------+
这张表的主键是 (user_id, page_id)。
这张表的每一行代表着 user_id 喜欢 page_id。

写一段 SQL 向user_id = 1 的用户,推荐其朋友们喜欢的页面。不要推荐该用户已经喜欢的页面。

你返回的结果中不应当包含重复项。

返回结果的格式如下例所示。

示例 1:

输入:
Friendship table:
+----------+----------+
| user1_id | user2_id |
+----------+----------+
| 1        | 2        |
| 1        | 3        |
| 1        | 4        |
| 2        | 3        |
| 2        | 4        |
| 2        | 5        |
| 6        | 1        |
+----------+----------+
Likes table:
+---------+---------+
| user_id | page_id |
+---------+---------+
| 1       | 88      |
| 2       | 23      |
| 3       | 24      |
| 4       | 56      |
| 5       | 11      |
| 6       | 33      |
| 2       | 77      |
| 3       | 77      |
| 6       | 88      |
+---------+---------+
输出:
+------------------+
| recommended_page |
+------------------+
| 23               |
| 24               |
| 56               |
| 33               |
| 77               |
+------------------+
解释:
用户1 同 用户2, 3, 4, 6 是朋友关系。
推荐页面为: 页面23 来自于 用户2, 页面24 来自于 用户3, 页面56 来自于 用户3 以及 页面33 来自于 用户6。
页面77 同时被 用户2 和 用户3 推荐。
页面88 没有被推荐,因为 用户1 已经喜欢了它。

解题

1.找到user_id=1的亲密朋友(通过union all)

2.找到亲密朋友爱看的书

3.根据亲密朋友爱看的书和自己看过的书,获得推荐的书

select distinct page_id as recommended_page
from Likes
where user_id in(
    select user1_id as user_id from Friendship where user2_id=1
    union all
    select user2_id as user_id from Friendship where user1_id=1
)and page_id not in(
    select page_id from Likes where user_id=1
)

或者可以将union all替换成case when…then…语句

select distinct page_id as recommended_page
from Likes
where user_id in(
    select 
        case
        when user1_id=1 then user2_id
        when user2_id=1 then user1_id
        end
    from Friendship
    where user1_id=1 or user2_id=1
)and page_id not in(
    select page_id from Likes where user_id=1
);
相关文章
|
5月前
|
SQL 存储 Oracle
《SQL必知必会》个人笔记
《SQL必知必会》个人笔记
37 1
|
5月前
|
SQL 关系型数据库 MySQL
SQL常见面试题总结2
SQL常见面试题总结
93 2
|
5月前
|
SQL 关系型数据库 MySQL
SQL常见面试题总结1
SQL常见面试题总结
74 1
|
5月前
|
SQL 关系型数据库 数据库
《SQL必知必会》个人笔记(三)
《SQL必知必会》个人笔记(三)
45 0
|
5月前
|
SQL 存储 安全
《SQL必知必会》个人笔记(四)
《SQL必知必会》个人笔记(四)
41 0
|
5月前
|
SQL
leetcode-SQL-607. 销售员
leetcode-SQL-607. 销售员
28 0
|
5月前
leetcode-SQL-584. 寻找用户推荐人
leetcode-SQL-584. 寻找用户推荐人
30 0
|
5月前
|
SQL
leetcode-SQL-1890. 2020年最后一次登录
leetcode-SQL-1890. 2020年最后一次登录
30 0
|
12月前
|
SQL 关系型数据库 MySQL
15道常用sql面试题
15道常用sql面试题
196 0