복붙노트

[SQL] 상호 친구가 가입하여 SQL (MySQL의)

SQL

상호 친구가 가입하여 SQL (MySQL의)

나는 두 개의 테이블이

사용자 테이블 :

id|name

user_relationships

id | user_id | friend_id

2 사용자의 상호 친구의 이름을 싶어. 즉 :

user_relationships
1 | 1 | 3
2 | 2 | 3  

users
3| sammy

사용자 1과 2는 내가 한 쿼리에서 자신의 이름 '새미'싶어 3. 상호 친구가있다.

어떻게 그렇게 할 수 있습니까?

해결법

  1. ==============================

    1.

    SELECT id, name
    FROM users
    WHERE id IN (
      SELECT friend_id
      FROM user_relationships
      WHERE user_id IN ( 1, 2 )
      GROUP BY friend_id
      HAVING COUNT(friend_id) >= 2
    )
    

    또는 하나 조인

    SELECT friend_id, name
    FROM user_relationships r
      INNER JOIN users u ON r.friend_id = u.id
    WHERE user_id IN ( 1, 2 )
    GROUP BY friend_id
    HAVING COUNT(friend_id) >= 2
    
  2. ==============================

    2.당신은 다른 USER_ID 두 행이 동일한 friend_id을 가질 수 있도록, 자체 user_relationships에 가입해야

    당신은 다른 USER_ID 두 행이 동일한 friend_id을 가질 수 있도록, 자체 user_relationships에 가입해야

    모든 상호 친구 :

    select ur1.user_id user1, 
           ur2.user_id user2, 
           ur2.friend_id mutual_friend
    from   user_relationships ur1 
           JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
    where  ur1.user_id != ur2.user_id
    

    이름을 얻기 위해 사용자 테이블에 가입 :

    select ur1.user_id user_id1, 
            u1.name User1, 
           ur2.user_id user2, 
            u2.name User2,
           ur2.friend_id mutual_friend_id,
            u3.name mutual_friend
    from user_relationships ur1 
         JOIN user_relationships ur2 ON  ur1.friend_id = ur2.friend_id
         JOIN user u1 ON u1.user_id = ur1.user_id
         JOIN user u2 ON u1.user_id = ur2.user_id
         JOIN user u3 ON ur1.user_id = u3.user_id
    where ur1.user_id != ur2.user_id
    

    당신은 일부 특정 사용자를위한 상호 친구를 필터링 할 수 있습니다 사용 ur1.user_id = first_user 및 ur2.user_id = second_user

  3. ==============================

    3.당신이 뭔가를 시도 할 수 있습니다 :

    당신이 뭔가를 시도 할 수 있습니다 :

    select id, name from users where id in 
        (select friend_id from user_relationships where user_id = @user1_id and friend_id in 
            (select friend_id from user_relationships where user_id = @user2_id)
        )
    

    이것은 @ user1_id하고 @ user2_id ID를 가진 모든 사용자 상호 친구 반환해야합니다. 그것은 아직 테스트하지,하지만 시작 지점을 제공합니다 ...

  4. ==============================

    4.[아니오]를 확인하지 않았지만,이 쿼리는 ID 당신에게 관련 사용자 이름의 목록을 제공해야한다.

    [아니오]를 확인하지 않았지만,이 쿼리는 ID 당신에게 관련 사용자 이름의 목록을 제공해야한다.

    select u1.name, u2.name 
      from users as u1
      join user_relationships as ur
        on u1.id = ur.user_id
      join users as u2
        on ur.friend_id = u2.id
      where U1.id = [no];
    

    (USER_ID, friend_id) 이미 합법적 인 기본 키와 같이 BTW, 당신은 당신의 교차 테이블에 대한 인공 ID를 필요가 없습니다.

  5. from https://stackoverflow.com/questions/6731514/mutual-friends-sql-with-join-mysql by cc-by-sa and MIT license