【问题标题】:SQL - How to select master records that have no detail records?SQL - 如何选择没有详细记录的主记录?
【发布时间】:2014-12-03 10:18:46
【问题描述】:

我有两个表(表 1 - 主表,表 2 - 详细表)。如何仅从主表中选择(查看)那些在明细表中没有记录的记录?我可以为此使用什么 SQL 语句?我正在使用 MS SQL Server 2012。

编辑:表定义

表 1 - ID (PK) Table2 - ID (PK), Table1ID (FK)

【问题讨论】:

  • 两个表中的记录是否共享相同的ID?
  • Table1 - ID (PK) 和 Table2 [ID (PK), Table1ID (FK)]

标签: sql sql-server


【解决方案1】:

使用NOT IN 运算符

SELECT *
    FROM   Table1
    WHERE  ID NOT IN(SELECT Table1ID
                           FROM   Table2 ) 

【讨论】:

    【解决方案2】:

    我会使用NOT EXISTS,因为它清晰、高效并且对可空列没有任何问题。

    例如(MasterID 是 PK/FK):

    SELECT master.*
    FROM dbo.Table1 master
    WHERE NOT EXISTS
    (
        SELECT 1 FROM Table2 detail
        WHERE detail.MasterID = master.MasterID
    )
    

    但您还有其他选择:http://sqlperformance.com/2012/12/t-sql-queries/left-anti-semi-join

    【讨论】:

      【解决方案3】:

      使用排他(左)外连接怎么样?

       SELECT 
             master.* 
       FROM 
             master LEFT OUTER JOIN details 
       ON    master.ID = details.masterID         
       WHERE details.ID IS NULL;
      

      查看here 以获得更详细的说明,为什么此查询是此类问题的解决方案。

      【讨论】:

        【解决方案4】:

        我更喜欢在这种情况下使用左连接:

        select tp.*
        from   table_parent tp
               left join table_child tc on tc.parent_id = tp.id
        where  tc.parent_id is null
        

        【讨论】:

          【解决方案5】:

          这将极大地帮助您回答您的问题:

          http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

          SELECT column1 FROM t1 WHERE NOT EXISTS (SELECT * FROM t2);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-05-24
            • 1970-01-01
            • 2021-08-31
            • 1970-01-01
            • 1970-01-01
            • 2014-10-26
            • 1970-01-01
            相关资源
            最近更新 更多