Oracle中有两列的主键?

时间:2016-03-30 14:20:46

标签: oracle oracle11g foreign-keys primary-key composite-primary-key

我有emp1和emp2的表

EMP1:

emp_1 | emp_2
1     | 2
3     | 4
5     | 6

EMP2:

emp
1
2
3
6

我尝试将主键设置为表emp1,将外键设置为emp2。

我的代码:

主键:

alter table emp1 add primary key(emp_1,emp_2);

对于外键:

alter table emp2
add foreign key (emp)
references a_t1(emp_1,emp_2);

错误:

Error report -
SQL Error: ORA-02256: number of referencing columns must match referenced       columns
02256. 00000 -  "number of referencing columns must match referenced columns"
*Cause:    The number of columns in the foreign-key referencing list is not
       equal to the number of columns in the referenced list.
*Action:   Make sure that the referencing columns match the referenced
       columns.

请帮我解决此错误并设置主键。

1 个答案:

答案 0 :(得分:1)

我能想到的唯一方法就是讨厌物化视图。最好修复您的数据,这样您就不会将主键分布在两列中。

CREATE TABLE EMP1 (
  EMP_1 INT UNIQUE,
  EMP_2 INT UNIQUE,
  PRIMARY KEY ( EMP_1,EMP_2 )
);

CREATE MATERIALIZED VIEW LOG ON EMP1
   WITH SEQUENCE, ROWID(EMP_1, EMP_2)
   INCLUDING NEW VALUES;

CREATE MATERIALIZED VIEW EMP1_MV
   BUILD IMMEDIATE
   REFRESH FAST ON COMMIT
   AS SELECT EMP_1 AS EMP
      FROM   EMP1
      UNION ALL
      SELECT EMP_2
      FROM   EMP1;

ALTER TABLE EMP1_MV ADD CONSTRAINT EMP1_MV__PK PRIMARY KEY ( EMP );

CREATE TABLE EMP2 (
  EMP INT PRIMARY KEY REFERENCES EMP1_MV( EMP )
);