Can I get better performance using a JOIN or using EXISTS?

前端 未结 12 1846
鱼传尺愫
鱼传尺愫 2020-12-03 13:04

I have two tables Institutions and Results and I want to see if there are any results for institutions that way I can exclude the ones that don\'t have results.

Can

12条回答
  •  悲哀的现实
    2020-12-03 14:09

    A LEFT OUTER JOIN will tend to perform better than a NOT EXISTS**, but in your case you want to do EXISTS and using a simple INNER JOIN doesn't exactly replicate the EXISTS behavior. If you have multiple Results for an Institution, doing the INNER JOIN will return multiple rows for that institution. You could get around that by using DISTINCT, but then the EXISTS will probably be better for performance anyway.

    ** For those not familiar with this method:

    SELECT
         MyTable.MyTableID
    FROM
         dbo.MyTable T1
    LEFT OUTER JOIN dbo.MyOtherTable T2 ON
         T2.MyTableID = T1.MyTableID
    WHERE
         T2.MyOtherTableID IS NULL
    

    is equivalent to

    SELECT
         MyTable.MyTableID
    FROM
         dbo.MyTable T1
    WHERE NOT EXISTS (SELECT * FROM MyOtherTable T2 WHERE T2.MyTableID = T1.MyTableID)
    

    assuming that MyOtherTableID is a NOT NULL column. The first method generally performs faster than the NOT EXISTS method though.

提交回复
热议问题