是否可以使用CTE语句从查询中创建表? 类似的东西:
CREATE TABLE db1.test1 AS
(
WITH cte1(v1) as
( SEL v1 FROM db1.table1 )
SEL * FROM cte1
)
这就是CTE的样子:
WITH employees(id, name, boss, senior_boss) AS
(
SEL
empls.id,
empls.name,
supervisors.name as boss,
senior_bosses.name as senior_boss
FROM empl_cte AS empls
LEFT JOIN empl_cte AS supervisors ON empls.boss_id = supervisors.id
LEFT JOIN empl_cte AS senior_bosses ON supervisors.boss_id = senior_bosses.id
),
WITH empl_cte(....) AS
(
SEL
id,
name
boss_id
FROM all_employees
WHERE <some_filters>
)
SEL
*
FROM products
LEFT JOIN employees ON products.sales_rep_id = employees.id
两者
和
employees
转换为子查询(empl_cte
作为VIEW)会导致性能大幅下降(运行时间从几分钟到几天不等)。我无法弄清楚Teradata优化器的工作原理。
关于新重构查询的EXPLAIN
似乎表明LEFT JOIN
成为无数时间耗尽的产品加入。
答案 0 :(得分:1)
这将适用于 V16(可能还有更早的版本)。
CREATE TABLE myTable AS (
SELECT * FROM (
WITH x AS (
SELECT ...
FROM ...
WHERE ...
)
SELECT ...
FROM x ...
WHERE ...
) D
) WITH DATA PRIMARY INDEX (PK)
;
基本上,您需要将整个查询(包括 CTE)包装在带有别名的 SELECT 中。