gpt4 book ai didi

sql - 连接表同时保持 Null 值

转载 作者:行者123 更新时间:2023-12-04 17:59:00 26 4
gpt4 key购买 nike

我有两个表:

  • 用户:ID、名字、姓氏
  • 网络:user_id、friend_id、状态

  • 我想从用户表中选择所有值,但我想显示特定用户的状态(比如 id=2),同时将其他用户保持为 NULL。例如:
    如果我有用户:
    ? first_name  last_name
    ------------------------
    1 John Smith
    2 Tom Summers
    3 Amy Wilson

    在网络中:
    user_id   friend_id   status
    ------------------------------
    2 1 friends

    我想为所有其他用户搜索 John Smith,所以我想得到:
    id first_name  last_name   status
    ------------------------------------
    2 Tom Summers friends
    3 Amy Wilson NULL

    我尝试先执行 LEFT JOIN 然后执行 WHERE 语句,但它不起作用,因为它排除了与其他用户有关系但与此用户无关的行。

    我可以使用 UNION 语句来做到这一点,但我想知道是否有可能在没有 UNION 的情况下做到这一点。

    最佳答案

    你需要把你的情况写进ON LEFT JOIN的条款.

    Select
    u.first_name,
    u.last_name,
    n.status
    From users u
    Left Join networks n On ( ( n.user_id = 1 And n.friend_id = u.id )
    Or ( n.friend_id = 1 And n.user_id = u.id )
    Where u.id <> 1

    这应该会返回所有用户(除了 John Smith )和状态 friend如果 John Smith要么是这个用户的 friend ,要么这个用户是 John Smith 的 friend .

    关于sql - 连接表同时保持 Null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2554239/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com