IN vs. JOIN with large rowsets

前端 未结 12 1750
天命终不由人
天命终不由人 2020-11-30 20:45

I\'m wanting to select rows in a table where the primary key is in another table. I\'m not sure if I should use a JOIN or the IN operator in SQL Server 2005. Is there any si

12条回答
  •  青春惊慌失措
    2020-11-30 21:25

    They are different queries with different results. With the IN query you will get 1 row from table 'a' whenever the predicate matches. With the INNER JOIN query you will get a*b rows whenever the join condition matches. So with values in a of {1,2,3} and b of {1,2,2,3} you will get 1,2,2,3 from the JOIN and 1,2,3 from the IN.

    EDIT - I think you may come across a few answers in here that will give you a misconception. Go test it yourself and you will see these are all fine query plans:

    create table t1 (t1id int primary key clustered)
    create table t2 (t2id int identity primary key clustered
        ,t1id int references t1(t1id)
    )
    
    
    insert t1 values (1)
    insert t1 values (2)
    insert t1 values (3)
    insert t1 values (4)
    insert t1 values (5)
    
    insert t2 values (1)
    insert t2 values (2)
    insert t2 values (2)
    insert t2 values (3)
    insert t2 values (4)
    
    
    select * from t1 where t1id in (select t1id from t2)
    select * from t1 where exists (select 1 from t2 where t2.t1id = t1.t1id)
    select t1.* from t1 join t2 on t1.t1id = t2.t1id
    

    The first two plans are identical. The last plan is a nested loop, this difference is expected because as I mentioned above the join has different semantics.

提交回复
热议问题