sql - 使用计算和联接时的最佳实践
问题描述
当一个人有一个 SQL 查询时,我有一个关于最佳实践的一般问题,并且您想使用联接/子查询来计算度量,然后将其用于业务规则。我学到了两种特别的方法,但是随着我的职业发展和我认识的人越来越多,他们似乎更喜欢其他方法。
下面,我写了我所指的5个例子。请注意,它们并不是用来工作的 SQL 查询,只是显示不同方法的示例。
--Example 1: filtering in-line
select top 1
from [Temp Data] base
left join table1 t1 on base.key = t1.key
and t1.category = 1
and t1.status not in ('Voided', 'Deleted')
--Example 2: using where
select top 1
from [Temp Data] base
left join table1 t1 on base.key = t1.key
where t1.category = 1
and t1.status not in ('Voided', 'Deleted')
--Example 3: sub-query
select top 1
from [Temp Data] base
left join (select col1
from table1 t1
where category = 1
and status not in ('Voided', 'Deleted')
) t1 on base.key = t1.key
--Example 4: if exists
select top 1
,case
when exists (select col1
from table1 t1
where category = 1
and status not in ('Voided', 'Deleted')
and base.key = t1.key
) then 1
else 0
end
from [Temp Data] base
--Example 5: outer apply
select top 1
from [Temp Data] base
outer apply (select col1
from table1 t1
where category = 1
and status not in ('Voided', 'Deleted')
and base.key = t1.key
) t1
我想听听人们对不同方法的看法。
解决方案
查询做不同的事情。所以,你应该选择你想要的形式。
例如,第二个查询将left join
转换为内连接。
第四个根本没有过滤,只是设置一个标志。
第一个、第三个和第五个是等价的。我认为第一种方法是编写查询的更“传统”方式——或者至少我认为更多的人会这样写。(3) 中的子查询是多余的(尽管对性能没有损害)。并且cross apply
并非所有数据库都支持。
推荐阅读
- ios - 得到 NSUnknownKeyException' 的错误,原因:setValue:forUndefinedKey: 这个类不符合键描述的键值编码
- spring - Spring Boot应用程序无故关闭
- android - 使用套接字 wifip2p 发送文件列表
- css - 这个 CSS 代码对 wordpress 网站有什么影响?
- google-app-engine - 标准 App Engine 迁移到 Go 1.11 云构建失败
- react-native - 如何使用来自 React 本机平面列表的不同数据进入同一屏幕
- objective-c - 无法向 XPrinter 发送命令
- ionic4 - 运行 ionic cordova build android 时出错
- javascript - Safari 12.1 中的变换原点动画问题
- c++ - 如何使用带有共享指针的 Boost Asio 来解决“本地系统中止网络连接”的问题?