【问题标题】:Oracle Materialized Views with primary key带有主键的 Oracle 物化视图
【发布时间】:2018-02-27 22:36:18
【问题描述】:

我在下面创建了 Oracle 物化视图:

CREATE MATERIALIZED VIEW MyMV
REFRESH COMPLETE ON DEMAND
AS

SELECT t1.*
  FROM table1 t1, table2 t2 where t1.id=t2.id;

table1有主键,MV创建成功,但物化视图表中没有创建主键。

有没有其他方法可以用主键创建 MV?

【问题讨论】:

    标签: oracle primary-key materialized-views


    【解决方案1】:

    这是因为您的物化视图基于两个表,如果您基于具有主键的单个表创建视图,则在您的物化视图上创建主键。 如果需要,您仍然可以在之后创建索引:

    SQL> create table t1(id number);
    
    Table created.
    
    SQL> create table t2(id number);
    
    Table created.
    
    SQL> alter table t1 add primary key (id);
    
    Table altered.
    
    SQL> alter table t2 add primary key (id);
    
    Table altered.
    
    SQL> CREATE MATERIALIZED VIEW MyMV
    REFRESH COMPLETE ON DEMAND
    AS
    SELECT t1.*
      FROM t1, t2 where t1.id=t2.id;  2    3    4    5
    
    Materialized view created.
    
    SQL> create unique index myindex on MyMV(id);
    
    Index created.
    

    编辑

    创建一个主键而不是唯一索引:

    SQL> alter materialized view MyMV add constraint PK_ID primary key (id);
    
    Materialized view altered.
    
    SQL> alter table t3 add constraint FK_TABLE3_MyMV foreign key (id) references MyMV (id);
    
    Table altered.
    

    【讨论】:

    • 但是我需要一个主键,因为我想在这个 MV 表中添加一个新的外键。在这种情况下,我需要创建主键而不是索引
    • 这是一个主键。当您在创建表时使用主键语法时,它会在后台创建唯一索引,进行测试。
    • 当我尝试创建 FK "alter table table3 add constraint FK_TABLE3_MyMV foreign key (id) references MyMV (id);" 时,我收到了错误 "ORA-02270: no matching unique or primary key for this column-list"。如果我更改创建主键的表工作正常
    • 有没有办法从原始表中“克隆”所有约束?
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 2018-08-24
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多