0
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;

these are my tables I don't know why it displays "Cannot add foreign key constraint" please help

2
  • 1
    change the order, one table needs to exist before the other.. Commented Aug 10, 2015 at 12:35
  • thank you :))))))))))))) Commented Aug 10, 2015 at 12:44

1 Answer 1

1

First create tblVoucher table then reference it in tblTransaction table

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

Sign up to request clarification or add additional context in comments.

1 Comment

be careful with wide PK's like you have in tblTransaction table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.