首页 > 解决方案 > 在物化视图中使用 union 或 union all 导致 PostgreSQL 错误

问题描述

我正在创建一个包含联合查询的物化视图,并收到以下错误:列“column1”指定了不止一次。

此错误的潜在原因是什么?

我该如何解决这个问题?

这是我的代码的示例:

CREATE MATERIALIZED VIEW schema.view_name_mv
(
     "column1",
     "column2",
     "column3"
)
as 
select 
     tn1.column1, 
     tn1.column2,
     tn1.column3
from schema.table_name1 tn1,
     schema.table_name2 tn2
where tn1.column1 = tn2.column1
and   tn1.column2  = tn2.column2
union all 
select 
     tn1.column1, 
     tn1.column2, 
     tn1.column3
from schema.table_name1 tn1, 
     schema.table_name3 tn3
where tn1.column1 = tn3.column1
and   tn1.column2 = tn3.colum2;

注意:在 PGAdmin 4 中独立运行查询将运行良好,但使用相同的查询创建物化视图将引发上面列出的错误。

标签: sqlpostgresqlunion-allmaterialized-viewspostgresql-10

解决方案


当您连接表并且当两个列具有相同名称时您没有指定哪个列属于每个表时会发生此错误。我想这些值 column1、column2 和 column3 是假的,并且由于它们充满了如下所示的 sintax 错误,我真的不知道在您的真实代码中您是否忘记重命名列。

尝试在你的真实代码中寻找这样的东西:

select column1 from 
schema.table1 tn1, schema.table2 tn2 
where tn1.column1 = tn2.column2

在此示例中,如果column1来自 table1 或 table2,则未指定

此示例中的 Sintax 错误:

CREATE MATERIALIZED VIEW schema.view_name_mv
(
     "column1",
     "column2",
     "column3", << remove this comma
)


union all 
select 
     tn1.colum1, << the name here is wrong, replace to column1
     tn1.colum2, << the name here is wrong, replace to column2
     tn1.column3

推荐阅读