Description
Table: Friendship
| Column Name | Type |
|---|---|
| user1_id | int |
| user2_id | int |
- (
user1_id,user2_id) is the primary key (combination of columns with unique values) for this table. - Each row of this table indicates that there is a friendship relation between
user1_idanduser2_id.
Table: Likes
| Column Name | Type |
|---|---|
| user_id | int |
| page_id | int |
- (
user_id,page_id) is the primary key (combination of columns with unique values) for this table. - Each row of this table indicates that
user_idlikespage_id.
Problem Statement
Write a solution to recommend pages to the user with user_id = 1 using the pages that your friends liked. It should not recommend pages you already liked.
Return result table in any order without duplicates.
The result format is in the following example.
Example 1:
Input:
Friendshiptable:
| user1_id | user2_id |
|---|---|
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 3 |
| 2 | 4 |
| 2 | 5 |
| 6 | 1 |
Likestable:
| user_id | page_id |
|---|---|
| 1 | 88 |
| 2 | 23 |
| 3 | 24 |
| 4 | 56 |
| 5 | 11 |
| 6 | 33 |
| 2 | 77 |
| 3 | 77 |
| 6 | 88 |
Output:
| recommended_page |
|---|
| 23 |
| 24 |
| 56 |
| 33 |
| 77 |
Explanation:
- User one is friend with users 2, 3, 4 and 6.
- Suggested pages are 23 from user 2, 24 from user 3, 56 from user 3 and 33 from user 6.
- Page 77 is suggested from both user 2 and user 3.
- Page 88 is not suggested because user 1 already likes it.
Solution
You need to find page recommendations for user_id = 1 using the pages liked by their friends. The recommendations should not include the pages already liked by this user. The problem has three components.
- Find pages liked by
user_id = 1. - Find friends of
user_id = 1. - Find distinct pages liked by these list of friends.
You can find pages liked by user_id = 1 using simple query like this. You will need to exclude this from the list of page recommendations using NOT IN clause.
1SELECT page_id FROM Likes WHERE user_id = 1
To find friends, you can check either user1_id or user2_id. The friendship can be one way as well.
1SELECT user2_id AS user_id FROM Friendship WHERE user1_id = 1
2UNION
3SELECT user1_id AS user_id FROM Friendship WHERE user2_id = 1
The same query can also be written using CASE WHEN clause.
1SELECT
2 CASE
3 WHEN user1_id = 1 THEN user2_id
4 WHEN user2_id = 1 THEN user1_id
5 END AS user_id
6 FROM Friendship
7 WHERE user1_id = 1 OR user2_id = 1
| user_id |
|---|
| 6 |
| 2 |
| 3 |
| 4 |
The last part is to find pages liked by above set of users. This you can find using DISTINCT page_id clause.
1SELECT DISTINCT page_id
2 FROM Likes
The final solution looks like this.
1SELECT DISTINCT page_id AS recommended_page
2 FROM Likes
3 WHERE user_id IN (
4 SELECT user1_id user_id FROM Friendship WHERE user2_id = 1
5 UNION
6 SELECT user2_id user_id FROM Friendship WHERE user1_id = 1
7) AND page_id NOT IN (
8 SELECT page_id FROM Likes WHERE user_id = 1
9)


Comments