【问题标题】:SQL extract unique data from two columns in same tableSQL从同一个表的两列中提取唯一数据
【发布时间】:2018-01-14 00:29:52
【问题描述】:

我有一个朋友表,其中包含以下列: friend_id 和friend_of(都存储了唯一的用户ID) 假设表朋友包含以下数据:

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

所以这意味着:
id=123 的用户有一个 id=456 的朋友
id=456 的用户有两个 ids=123 (friend_1) & 789(friend_2)的朋友
id=789 的用户有一个 id=456 的朋友

我想编写一个查询,给定一个用户 ID,显示该用户拥有的每个朋友(以及他们的 ID)。

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

你能帮我解决我需要的查询吗?

【问题讨论】:

    标签: sql multiple-columns


    【解决方案1】:

    您可以使用查询SELECT * FROM friends WHERE friend_id='456',它应该得到456 的所有朋友。然后使用外键friend_of 连接您的“用户”表。

    编辑:我没有意识到朋友是双向的关系。在这种情况下,请先使用 UNION,其他一些响应会谈到它。 :)

    【讨论】:

      【解决方案2】:

      只需使用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 
      

      【讨论】:

        【解决方案3】:
        (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,因为需要唯一值。

        【讨论】:

          【解决方案4】:

          选择friend_id,friend_of 其中friend_id = '456'

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-19
            • 2016-10-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多