外键约束

当创建外键约束的时候,子表所参照的父表需要有主键约束,或者是唯一约束,记住这里是约束,不是 unique index

这样就可以
create table dept1(deptno integer not null, deptname varchar(30))
alter table dept1 add constraint uk1_dept unique (deptno)
create table emp1(empno integer not null, deptno integer not null, empname varchar(30))
alter table emp1 add constraint uk1_emp1 foreign key (deptno) references dept1(deptno)

但是这样不行
create table dept1(deptno integer not null, deptname varchar(30))
create unique index ix1_dept1 on dept1(deptno)
create table emp1(empno integer not null, deptno integer not null, empname varchar(30))
alter table emp1 add constraint uk1_emp1 foreign key (deptno) references dept1(deptno)

报错信息:
db2 => alter table emp1 add constraint uk1_emp1 foreign key (deptno) references dept1(deptno)
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0573N  A column list specified in the references clause of constraint
"UK1_EMP1" does not identify a unique constraint of the parent table or
nickname "DB2INST1.DEPT1".  SQLSTATE=42890
db2 =>

请使用浏览器的分享功能分享到微信等