首页 > 解决方案 > 嵌套 CTE 的 SQL

问题描述

现在我的 SQL 代码如下:

WITH cte1 as(....),
     cte2 as(....),
     cte3 as (...)
select * 
from cte1 
left join cte2
on cte1.col1=cte2.col2
left join cte3
on cte1.col2=cte3.col3

现在我想使用上面的 SQL 代码根据结果进行进一步的查询(例如过滤器)。我尝试使用嵌套的 WITH 语句,但它不支持。

WITH a as (
WITH cte1 as(....),
     cte2 as(....),
     cte3 as (...)
select * 
from cte1 
left join cte2
on cte1.col1=cte2.col2
left join cte3
on cte1.col2=cte3.col3
)

是否有任何有效的方法可以根据上述 SQL 代码的结果进行进一步查询?

标签: sqlcommon-table-expression

解决方案


埃里克,你不嵌套它们,只是序列:

WITH cte1 as(....),
     cte2 as(....),
     cte3 as (...), 
another_cte as 
  (
  select * 
  from cte1 
  left join cte2
  on cte1.col1=cte2.col2
  left join cte3
  on cte1.col2=cte3.col3
  )

select <whatever> from another_cte

至于efficient way to do further query 您可能对“非 SQL”感兴趣,并将原始查询的结果保存在临时表或变量中。根据您使用的数据库,执行计划可能会更快/更慢,因此请检查一下。


推荐阅读