无法添加外键约束

时间:2015-08-10 12:32:50

标签: mysql

CREATE TABLE tblTransaction (
   strTransCode VARCHAR(50) NOT NULL,
   dtmTransDate datetime,
   strTransDesc VARCHAR(50) NOT NULL,
   dblTransAmt double,
   intVoucRefCodeTrans INT,
   FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
   PRIMARY KEY (strTransCode)
   )ENGINE=InnoDB;
CREATE TABLE tblVoucher (
   intVoucRefCode INT,
   strVoucRefDesc VARCHAR(50) NOT NULL,
   dtmVoucDate datetime,
   PRIMARY KEY (intVoucRefCode)
   )ENGINE=InnoDB;

这些是我的表我不知道为什么显示“无法添加外键约束”请帮忙

1 个答案:

答案 0 :(得分:1)

首先创建tblVoucher表,然后在tblTransaction

中引用它
CREATE TABLE tblVoucher (
   intVoucRefCode INT,
   strVoucRefDesc VARCHAR(50) NOT NULL,
   dtmVoucDate datetime,
   PRIMARY KEY (intVoucRefCode)
   )ENGINE=InnoDB;

CREATE TABLE tblTransaction (
   strTransCode VARCHAR(50) NOT NULL,
   dtmTransDate datetime,
   strTransDesc VARCHAR(50) NOT NULL,
   dblTransAmt double,
   intVoucRefCodeTrans INT,
   FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
   PRIMARY KEY (strTransCode)
   )ENGINE=InnoDB;

DEMO