inblog logo
|
silver
    SQL문제풀기

    [SQL문제풀기] 세 명이 서로 친구인 관계 찾기

    silver's avatar
    silver
    Mar 25, 2025
    [SQL문제풀기] 세 명이 서로 친구인 관계 찾기
    Contents
    문제SQLite

    문제

    solvesql.com
    solvesql.com
    https://solvesql.com/problems/friend-group-of-3/

    SQLite

    내가 작성한 정답1

    : 정답처리 되기 하지만 where 조건에 a.user_a_id < b.user_a_id and b.user_a_id < c.user_b_id를 넣으니까 시간이 너무 많이 소요된다.
    select a.user_a_id user_a_id, b.user_a_id user_b_id, c.user_b_id user_c_id from edges a join edges b on a.user_b_id = b.user_a_id join edges c on a.user_a_id = c.user_a_id and b.user_b_id = c.user_b_id where 3820 in (a.user_a_id,b.user_a_id,c.user_b_id) and (a.user_a_id < b.user_a_id and b.user_a_id < c.user_b_id)

    내가 작성한 정답2

    : where 조건에 a.user_a_id < b.user_a_id and b.user_a_id < c.user_b_id를 빼도 join 조건에서 a테이블의 b_id와 b테이블의 a_id 그리고 b테이블의 b_id, c테이블의 b_id를 같다는 조건으로 결합시켰기 때문에 위의 조건을 만족하므로 where절에 부등호 조건을 넣지 않아도 된다.
    select a.user_a_id user_a_id, b.user_a_id user_b_id, c.user_b_id user_c_id from edges a join edges b on a.user_b_id = b.user_a_id join edges c on a.user_a_id = c.user_a_id and b.user_b_id = c.user_b_id where 3820 in (a.user_a_id,b.user_a_id,c.user_b_id)

    내가 작성한 정답3

    : where 조건에 in 대신 or로 조건을 연결했다.
    → in 조건이 더 빠른 것으로 알고 있었으나 이 쿼리에서는 or 조건이 더 빨랐다.
    select a.user_a_id user_a_id, a.user_b_id user_b_id, b.user_b_id user_c_id from edges a join edges b on a.user_b_id = b.user_a_id join edges c on a.user_a_id = c.user_a_id and b.user_b_id = c.user_b_id where a.user_a_id = 3820 or b.user_a_id = 3820 or c.user_b_id = 3820
     
    Share article

    silver

    RSS·Powered by Inblog