如何从复合键创建外键?

时间:2013-06-27 09:16:02

标签: mysql ddl

我想从主键创建一个外键并得到此错误'#1005 - 无法创建表'

这是使用的DDL ......

CREATE TABLE Invoice
(
InvoiceID SMALLINT,
TaskID SMALLINT,
FOREIGN KEY Invoice(InvoiceID) REFERENCES XTABLE(InvoiceID),
PRIMARY KEY (InvoiceID, TaskID)
);

1 个答案:

答案 0 :(得分:0)

确保XTABLEInvoice中的关键列标记为PRIMARY KEYNOT NULL

CREATE TABLE XTABLE(InvoiceID SMALLINT NOT NULL, PRIMARY KEY(InvoiceID));

CREATE TABLE Invoice ( 
  InvoiceID SMALLINT NOT NULL, 
  TaskID SMALLINT NOT NULL,
  PRIMARY KEY (InvoiceID, TaskID),
  CONSTRAINT FOREIGN KEY Invoice(InvoiceID) REFERENCES XTABLE(InvoiceID)
);

SQL FIDDLE: http://sqlfiddle.com/#!2/5a56f