How to do WHERE clause BEFORE INNER JOIN

我是研究僧i 提交于 2019-12-10 14:56:34

问题


How I do query like this ?

select Distinct  Station  , Slot , SubSlot, CompID , CompName 
from DeviceTrace as DT DT.DeviceID = '1339759958' 
inner join CompList as CL  
where  and DT.CompID = CL.CompID

I need to do DT.DeviceID = '1339759958' before I start with the inner join. I work with sql server.


回答1:


I find it difficult to believe that it makes any difference. The query optimiser should apply the predicate before the join if it calculates that it is more efficient to do so. The only circumstance where you might need to do this is when the optimiser makes an erroneous choice (for inner joins at least -- there are valid cases for outer joins).




回答2:


try adding in ON clause.

SELECT DISTNCT Station, Slot, SubSlot, CompID, CompName 
FROM   DeviceTrace AS DT INNER JOIN CompList AS CL 
        ON  DT.CompID = CL.CompID AND
            DT.DeviceID = '1339759958'

In this case, the result is the same since you are doing INNER JOIN. Adding the condition in the ON clause can be very different when doing LEFT JOIN and filtering on the right hand side table.




回答3:


You can use a subquery to apply a where clause before a join:

select  *
from    (
        select  *
        from    DeviceTrace
        where   DeviceID = '1339759958' 
        ) as DT 
inner join 
        CompList as CL  
on      DT.CompID = CL.CompID

Although in this case, it should not matter whether you filter in a subquery, the on clause, or even the final where.




回答4:


A small clarification to answer from David Aldridge. You must use query

select Distinct  Station  , Slot , SubSlot, CompID , CompName 
from DeviceTrace as DT 
inner join CompList as CL on DT.CompID = CL.CompID  
where DT.DeviceID = '1339759958'


来源:https://stackoverflow.com/questions/16632901/how-to-do-where-clause-before-inner-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!