-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1264. Page Recommendations.sql
More file actions
51 lines (49 loc) · 1.48 KB
/
1264. Page Recommendations.sql
File metadata and controls
51 lines (49 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
-- Write an SQL query 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.
SELECT DISTINCT page_id AS recommended_page
FROM Likes l
JOIN Friendship f
ON (f.user1_id = 1 AND l.user_id = f.user2_id) OR (f.user2_id = 1 AND l.user_id = f.user1_id) -- All friends of user1 = 1 or user2 = 1
WHERE page_id NOT IN (SELECT page_id FROM Likes WHERE user_id = 1)
/* GROUP BYInput:
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 |
+---------+---------+
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.
*/