简体   繁体   中英

SQL Server Query - Best Practice on Where Clause

Take a look into this query:

Select 
    b.CodCred, 
    b.Codigo, 
    c.Nome 
from 
    AS_CredenciadosUsu a 
inner join 
    AS_Credenciados b on a.CodCred=b.CodCred 
inner join 
    Cadastro c on b.Codigo=c.Codigo 
Where 
    a.NumContrato = 21 and 
    b.NumContrato = 21 and 
    c.NumContrato = 21 and 
    a.CodUsuD = 1

I must set the column NumContrato in those 3 tables.

Is there a best practice to do this into this query? This just look dirty to me, but I don't know how to do better or if exist any method to do this better.

Thanks.

It looks like you should have the NumContrato field as a join condition if they are actually related in all three tables.

Then in your WHERE clause, where you should be filtering -- not joining -- you can just specify the criteria one time.

Ie.

Select b.CodCred, b.Codigo, c.Nome
  from AS_CredenciadosUsu a
 inner join AS_Credenciados b
    on a.CodCred = b.CodCred
   and a.NumContrato = b.NumContrato
 inner join Cadastro c
    on b.Codigo = c.Codigo
   and c.NumContrato = b.NumContrato
 Where a.NumContrato = 21
   and a.CodUsuD = 1

This should let the engine work better and it makes it easier to read and maintain for you also:

Select 
    b.CodCred, 
    b.Codigo, 
    c.Nome 
from AS_CredenciadosUsu a 
join AS_Credenciados    b on a.NumContrato=b.NumContrato and a.CodCred=b.CodCred 
join Cadastro           c on b.NumContrato=c.NumContrato and b.Codigo=c.Codigo 
Where 
    a.NumContrato=21 and 
    a.CodUsuD=1

This way you have all conditions that link b to a in the join clause of b... all conditions that link c to b in the join clause of c... and all conditions on a in the WHERE clause. The constants (21 and 1) are used only once, and they can also be more easily replaced with a parameter if the need arises.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM