dongxun5349 2015-07-21 01:52
浏览 6
已采纳

在这种情况下如何查询两个表?

For the one who down voted the question, could you please explain to me the reason? If this seems trivial to you, I would appreciate you pointing me to a reference; If this is a duplicate question, I would appreciate you pointing me to the earlier question. Thanks!

I have two tables, user and friend. The goal is as follows: A user a wants to get the information of another user b; the returned info depends on whether they are friends or not. To be concrete, if they are friends, a can see b's username and address; if not, a can only see b's username.

user table looks like:

id   username   address
1    abc        XXXX Rd. XXXX
2    def        XXXX Rd. XXXX
3    ghi        XXXX Rd. XXXX

friend table looks like:

id   id1   id2
1    1     2     // so 1 (abc) and 2 (def) are friends
2    1     3     // so 1 (abc) and 3 (ghi) are friends

2 (def) and 3 (ghi) are not friends. So basically there are the following two scenarios:

  1. user 2 (def) want to see user 3 (ghi)'s info, the query returns ghi's username only but not address
  2. user 1 (abc) want to see user 3 (ghi)'s info, the query returns ghi's username and address

Is it possible to do it using one query?

  • 写回答

2条回答 默认 最新

  • doulei6330 2015-07-21 02:17
    关注

    You can use a JOIN and check that the joined user's column exists (is not null) to determine if the friendship exists.

    E.g. if user def (2) wants info on user ghi (3):

    SELECT
      user.username,
      user.address,
      friend.id AS are_friends
    FROM user
    INNER JOIN friend
      ON (friend.id1 = user.id AND friend.id2 = 2)
    WHERE user.id = 3;
    

    This should only return a row from your PDO handler if the link between user 2 and 3 exists. If it doesn't, the inner join will not work - if you used a left join here it would, but would return null for the are_friends field.

    Of course you would replace 2 in that query with the current logged in user's ID, and replace 3 with the ID of the user that you want information for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c