当我在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不允许为此表类型添加外键约束。
答案 0 :(得分:5)
当您查看documentation for dashDB(而不是DB2)时,您会注意到可以创建外键。但是,默认情况下会创建一个按列组织的表。仅支持非强制参照约束。在您的示例中,您需要在语句中添加NOT ENFORCED:
ALTER TABLE EMPLOYEE
ADD CONSTRAINT EMPLOYEE_DEPARTMENT_FK FOREIGN KEY (depname )
REFERENCES DEPARTMENT ( depname ) NOT ENFORCED;
答案 1 :(得分:2)
默认情况下,在CREATE上,Bluemix上的DashDB表按列排列' ... https://www-01.ibm.com/support/knowledgecenter/SSEPGG_10.5.0/com.ibm.db2.luw.admin.dbobj.doc/doc/c0060592.html
这也将禁止为此表类型添加外键约束。
要添加FK,请在ORGANIZE BY ROW
语句中添加CREATE TABLE
:
CREATE TABLE DEPARTMENT (
depname CHAR (10) UNIQUE NOT NULL ,
phone INTEGER
) ORGANIZE BY ROW;
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)
) ORGANIZE BY ROW;
ALTER TABLE EMPLOYEE
ADD CONSTRAINT EMPLOYEE_PK PRIMARY KEY ( "EmpNr" ) ;
ALTER TABLE EMPLOYEE
ADD CONSTRAINT EMPLOYEE_DEPARTMENT_FK FOREIGN KEY (depname )
REFERENCES DEPARTMENT ( depname ) ;