[英]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. 我必须在这3个表中设置
NumContrato
列。
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. 如果所有三个表中的NumContrato字段实际上都相关,则应该将它们作为连接条件。
Then in your WHERE clause, where you should be filtering -- not joining -- you can just specify the criteria one time. 然后,在您的WHERE子句中,您应该在其中进行过滤(而不是加入),您只需指定一次条件即可。
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. 这样,您将拥有在b的join子句中将b链接到a的所有条件...在c ...的join子句中将c链接到b的所有条件以及WHERE子句中a的所有条件。 The constants (21 and 1) are used only once, and they can also be more easily replaced with a parameter if the need arises.
常量(21和1)仅使用一次,如果需要,也可以更轻松地用参数替换它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.