【问题标题】:How to select all records from one table that do not exist in another table but return NULL in the record that do not exist如何从一个表中选择在另一个表中不存在但在不存在的记录中返回NULL的所有记录
【发布时间】:2018-07-11 16:31:46
【问题描述】:

我有一个问题。我的数据库中有两个表,tableA 和 tableB。 tableB 包含来自 tableA 的数据,因为 tableB 是来自 tableA 主键的外键,反之亦然。如何从 tableB 中选择不包含在 tableA AS NULL 记录中的所有记录?

tableA field : field1, field2, field3
tableB field : field1, field2, field3, field4, ...

谢谢。

【问题讨论】:

    标签: sql-server sql-server-2014


    【解决方案1】:

    我不确定是不是这样

    CREATE TABLE #input_a (id INT)
    CREATE TABLE #input_b (id INT)
    
    INSERT INTO #input_a VALUES(1)
    INSERT INTO #input_a VALUES(2)
    INSERT INTO #input_a VALUES(3)
    INSERT INTO #input_a VALUES(4)
    
    INSERT INTO #input_b VALUES(1)
    INSERT INTO #input_b VALUES(5)
    INSERT INTO #input_b VALUES(3)
    INSERT INTO #input_b VALUES(6)
    
    
    SELECT b.id, a.id FROM #input_b as b LEFT JOIN #input_a as a ON b.id=a.id
    DROP TABLE #input_a
    DROP TABLE #input_b
    

    检查一下: https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=f447b6ff6f986d4bdfcda66a2be1b4c5

    【讨论】:

    • 我很高兴能帮上忙,祝你有美好的一天:) @FannyKaunang
    【解决方案2】:

    不妨试试以下方法:

    Select 
      * 
    From
      TableB
    LEFT JOIN
      TableB
      ON TableA.primary_key = TableB.foreign_key;
    

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 2015-08-27
      • 1970-01-01
      • 2022-11-13
      • 2016-02-29
      • 1970-01-01
      相关资源
      最近更新 更多