[ 알고리즘 ] LeetCode 1919. Leetcodify Similar Friends

이주 weekwith.me·2022년 6월 18일
0

알고리즘

목록 보기
16/73
post-thumbnail

블로그를 이전 중이라 완료되기 전까지는 벨로그에 작성할 계획입니다.
이후 모든 글은 https://weekwith.me 에 작성 예정이니 다른 글이 궁금하시다면 해당 링크를 통해 방문해주세요.

본 글은 [ LeetCode ] 1919. Leetcodify Similar Friends를 풀고 작성한 글입니다.

문제

테이블

Table: Listens

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| song_id     | int     |
| day         | date    |
+-------------+---------+
There is no primary key for this table. It may contain duplicates.
Each row of this table indicates that the user user_id listened to the song song_id on the day day.

Table: Friendship

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user1_id      | int     |
| user2_id      | int     |
+---------------+---------+
(user1_id, user2_id) is the primary key for this table.
Each row of this table indicates that the users user1_id and user2_id are friends.
Note that user1_id < user2_id.

요구사항

Write an SQL query to report the similar friends of Leetcodify users. A user x and user y are similar friends if:

  • Users x and y are friends, and
  • Users x and y listened to the same three or more different songs on the same day.

Return the result table in any order. Note that you must return the similar pairs of friends the same way they were represented in the input (i.e., always user1_id < user2_id ).

풀이

접근법

Friendship 테이블에 user1_id 필드와 Listens 테이블의 user_id 필드가 일치하는 본인이 들은 음악 리스트를 INNER JOIN 구를 사용해 결합하고 다시 이곳에 user2_id 필드와 다른 Listens 테이블의 user_id 필드, 그리고 기존에 결합했던 Listens 테이블과 song_idday 필드가 일치하는, 친구가 들은 음악 리스트를 INNER JOIN 구를 사용해 결합한다.

이후 user1_id , user2_id , 그리고 day 필드를 기준으로 GROUP BY 구를 통해 행을 묶은 뒤 HAVING 구에서 서로 다른 song_id 필드의 수가 세 개 이상인 행만 반환되게 하면 된다.

나의 풀이

접근법을 토대로 INNER JOIN 구를 두번 사용한 풀이는 아래와 같다.

SELECT DISTINCT user1_id, user2_id
FROM Friendship
JOIN Listens AS MyListens
ON Friendship.user1_id = MyListens.user_id
JOIN Listens AS FriendListens
ON (
    Friendship.user2_id = FriendListens.user_id
    AND
    MyListens.song_id = FriendListens.song_id
    AND
    MyListens.day = FriendListens.day
)
GROUP BY Friendship.user1_id, Friendship.user2_id, MyListens.day
HAVING COUNT(DISTINCT MyListens.song_id) >= 3;
profile
Be Happy 😆

0개의 댓글