How to find rows in one table that have no corresponding row in another table

后端 未结 6 757
甜味超标
甜味超标 2020-11-29 01:50

I have a 1:1 relationship between two tables. I want to find all the rows in table A that don\'t have a corresponding row in table B. I use this query:

SELEC         


        
6条回答
  •  臣服心动
    2020-11-29 02:18

    You can also use exists, since sometimes it's faster than left join. You'd have to benchmark them to figure out which one you want to use.

    select
        id
    from
        tableA a
    where
        not exists
        (select 1 from tableB b where b.id = a.id)
    

    To show that exists can be more efficient than a left join, here's the execution plans of these queries in SQL Server 2008:

    left join - total subtree cost: 1.09724:

    left join

    exists - total subtree cost: 1.07421:

    exists

提交回复
热议问题