简体   繁体   English

声明临时表与使用WITH语句

[英]Declaring a temp table vs.using a WITH statement

I work in market research and am in the process of getting a better understanding of best practices when writing SQL. 我从事市场研究,正在编写SQL时更好地理解最佳实践。

One of the situations that I have encountered is the use of the WITH clause and the use of declared temp tables. 我遇到的一种情况是使用WITH子句和使用声明的临时表。

In most cases I use the with clause as it is easy to implement (and I prefer it to cascaded SELECT s). 在大多数情况下,我使用with子句,因为它很容易实现(我更喜欢它级联SELECT )。

However, is there a benefit to using declared temp tables when it comes to run time and efficiency? 但是,在运行时和效率方面使用声明的临时表是否有好处? I am more looking for pros/cons of each. 我更喜欢每个人的利弊。

Most important is to get a correctly working query first. 最重要的是首先获得正确工作的查询。 Any query. 任何查询。

If it is to be reused many times, post it here and engineers will give opinion about how to improve it and perhaps how to measure its performance. 如果是多次重复使用,它张贴在这里和工程师将提供有关如何改进它,也许如何衡量其性能的意见。

Many factors are at play: the schema, software, edition, server distribution, number of inputs, number of outputs, etc. 许多因素在起作用:架构,软件,版本,服务器分布,输入数量,输出数量等。

This decision is case-by-case. 这个决定是逐案的。 A WITH clause is useful to 1) repeat a sub-query multiple times in an outer query and 2) to pull out a complex inner query from the outer query to keep things clean and readable. WITH子句对于1)在外部查询中多次重复子查询以及2)从外部查询中提取复杂的内部查询以保持内容清洁和可读是有用的。 A WITH can easily be replaced by a VIEW. 可以通过VIEW轻松替换WITH。 Think of it as an inline view. 将其视为内联视图。

I would argue a temp table is more specialized. 我认为临时表更专业。 A temp table is often used for caching when you need to keep a result set around during a session to be used by multiple queries. 当您需要在会话期间保留结果集以供多个查询使用时,临时表通常用于缓存。 There are other use cases, but again more specialized to the situation. 还有其他用例,但同样更专注于这种情况。

These two concepts are only "kind of" related. 这两个概念只是“有点”相关。

Depending on your scenario, neither a WITH or a temp table may be appropriate. 根据您的方案,WITH或临时表都不合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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