代码之家  ›  专栏  ›  技术社区  ›  Teo

SQL从同一表的两列中提取唯一数据

  •  1
  • Teo  · 技术社区  · 7 年前

    我有一个表friends,其中包含以下列:

    friend_id   |   friend_of
    -------------------------
       123      |     456    
       456      |     789    
       456      |     123
    


    id=123的用户有一个id=456的朋友
    id=456的用户有两个id=123的朋友(friend_1)(&789(friend_2)
    id=789的用户有一个id=456的friwnd

    例如:
    如果给定id=123的用户,则输出将是id=456的用户

    如果给定id=456的用户,则输出将是id=123和789的用户

    你能帮我回答我需要的问题吗?

    4 回复  |  直到 7 年前
        1
  •  2
  •   Rajeev Ranjan    7 年前
    (select friend_id as all_friends from friends where friend_of=ID) 
    uninon
    (select friend_of as all_friends from friends where friend_id=ID)
    

    我想您感兴趣的是一个id只存在于其中一列中的情况。上述查询将解决这一问题。请注意 union 在这里使用而不是 union all 因为需要唯一值。

        2
  •  0
  •   guru008    7 年前

    其中friend\u id='456'

    只需更改ID即可获得欲望输出

        3
  •  0
  •   haku    7 年前

    只需使用 union

    Declare @id int = 1;
    select f.friendof from 
    #YourTableName as f where f.friendId = @id
    union
    select f.friendId from 
    #YourTableName as f where f.friendof = @id 
    
        4
  •  0
  •   chenjesu    7 年前

    SELECT * FROM friends WHERE friend_id='456' ,这将获得456的所有好友。然后使用外键在“users”表上进行连接 friend_of .

    编辑:我没有意识到朋友是一种双向关系。在这种情况下,首先使用一个联合,其他一些回答会讨论它。:)