当我在Bluemix上的DashDB(DB2)中创建表时,如下所示:
CREATE TABLE DEPARTMENT (
depname CHAR (10) UNIQUE NOT NULL ,
phone INTEGER
) ;
ALTER TABLE DEPARTMENT ADD CONSTRAINT DEPARTMENT_PK PRIMARY KEY ( depname ) ;
CREATE TABLE EMPLOYEE (
"EmpNr" NUMERIC (3) UNIQUE NOT NULL ,
empname CHAR (20) ,
depname CHAR (10) ,
EMPLOYEE2_title CHAR (20)
);
ALTER TABLE EMPLOYEE ADD CONSTRAINT EMPLOYEE_PK PRIMARY KEY ( "EmpNr" ) ;
ALTER TABLE EMPLOYEE ADD CONSTRAINT EMPLOYEE_DEPARTMENT_FK FOREIGN KEY (depname ) REFERENCES DEPARTMENT ( depname ) ;
Bluemix不允许为此表类型添加外键约束。
最佳答案
当您查看documentation for dashDB(不是DB2)时,您会注意到可以创建外键。但是,默认情况下,表是按列组织创建的。仅支持非强制引用约束。在您的示例中,您需要在语句中添加NOT ENFORCED:
ALTER TABLE EMPLOYEE
ADD CONSTRAINT EMPLOYEE_DEPARTMENT_FK FOREIGN KEY (depname )
REFERENCES DEPARTMENT ( depname ) NOT ENFORCED;