Reputation: 915
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.
Upvotes: 0
Views: 869
Reputation: 3043
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.
Upvotes: 1
Reputation: 13248
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
Upvotes: 2