postgres中,with与手工create table 创建临时表,用完再drop table,在效率上有什么区别?

在一个存储过程中:

  1. with会创建临时表吗?存放在哪里?
  2. 如果with也会创建临时表,那么与手工create table 创建临时表,用完再drop table,在效率上有什么区别?
阅读 5k
2 个回答

参考https://www.postgresql.org/do...

WITH provides a way to write auxiliary statements for use in a larger query. These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.
WITH提供了一种编写辅助语句以便在更大的查询中使用的方法。这些语句(通常称为公用表表达式或CTE)可以被视为定义仅针对一个查询存在的临时表。

个人理解CTE也是一种临时表(postgre自己实现的), 比自己创建临时表效率更高,不过只在一次查询中有效。在多次查询的储存过程中用一次临时表效率肯定比多次with高

当drop table临时表 会对元数据表加排他锁,会对数据库的性能产生一些影响;
建议 如果逻辑固定,只在第一次创建中间表,每次truncate数据即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进