douque8861 2012-03-05 20:55
浏览 41
已采纳

MySQL表连接

I have a table which links the userID and the friendID (which is another user) to say they are friends. If User 1 adds User 24 as their friend, the first row in the below table will happen If User 10 adds User 1 as their friend, the second row in the below table will happen

From there, even if User 1 is on either side, they are friends with the adjacent ID.

FRIENDS TABLE:

userID | friendID
-----------------
   1   |    24
   10  |    1

What I need to do now is: If User 1 is logged in, I need to display the people they are friends with. This query I have wrote:

SELECT DISTINCT (Users.username), friends.userID, friends.friendID FROM Users, friends WHERE Users.userID IN(SELECT userID FROM friends WHERE Users.userID = friends.userID) OR Users.userID IN(SELECT DISTINCT(userID) FROM friends WHERE Users.userID = friends.friendID)

Will bring back:

username | userID | friendID
-----------------------------
   name1 |   10   |    1
   name1 |   1    |    24
   name2 |   10   |    1
   name2 |   1    |    24

name1 = ID 1 name2 = ID 10

Is there a way where I can retrieve the logged in Users'friends (e.g. if ID #1 is logged in) whether they appear in the userID or friendID columns. and then, in this case, retrieve ID 24 and 10 because they are linked with ID #1, and then when it comes to displaying, eliminate ID # 1 from the list because it will bring up that they are friends with themselves.

Hope this makes sense and thank you in advance!

  • 写回答

3条回答 默认 最新

  • doudou0111 2012-03-05 21:00
    关注

    Here's an easy way to do it with UNION. This also takes care of duplicates:

    (SELECT userID
    FROM friends
    WHERE friendID = 1)
    UNION
    (SELECT friendID
    FROM friends
    WHERE userID = 1)
    

    If you want to return usernames too, you can do your JOINs inside the subqueries:

    (SELECT f.userID, u.username
    FROM friends f
    JOIN users u
      ON u.userID = f.userID
    WHERE f.friendID = 1)
    UNION
    (SELECT f.friendID, u.username
    FROM friends f
    JOIN users u
      ON u.userID = f.friendID
    WHERE f.userID = 1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法