带主键的 Oracle 物化视图

Oracle Materialized Views with primary key

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

CREATE MATERIALIZED VIEW MyMV
REFRESH COMPLETE ON DEMAND
AS

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

table1有主键,MV创建成功,但在实体化视图中没有创建主键table。

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

这是因为你的物化视图是基于两个table的,如果你基于单个table创建你的视图并且有一个主键,那么主键是在你的物化视图上创建的. 如果需要,您仍然可以在之后创建索引:

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.