开发者

MySQL: Why doesn't this db creation script work?

开发者 https://www.devze.com 2022-12-21 17:24 出处:网络
For some reason, this MySQL fails: CREATE S开发者_StackOverflow社区CHEMA IF NOT EXISTS `partB` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;

For some reason, this MySQL fails:

CREATE S开发者_StackOverflow社区CHEMA IF NOT EXISTS `partB` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `partB`;

CREATE TABLE Employees ( ssn CHAR(11),
Name CHAR(30),
mlot INTEGER,
PRIMARY KEY(ssn))
ENGINE = InnoDB;

CREATE TABLE Dept_Mgr ( did INTEGER,
dname CHAR(20),
ssn CHAR(11) NOT NULL,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees
ON DELETE NO ACTION)
ENGINE = InnoDB;

It gives the error:

ERROR 1005 (HY000): Can't create table partb.dept_mgr (errno: 150)

What can be causing this?


You have to specify the column(s) in the foreign table for the key:

FOREIGN KEY (ssn) REFERENCES Employees (ssn) ...


This command:

SHOW ENGINE INNODB STATUS;

is your friend when you have trouble creating foreign keys. Output (abridged)

------------------------
LATEST FOREIGN KEY ERROR
------------------------
100225  2:51:42 Error in foreign key constraint of table test/dept_mgr:
FOREIGN KEY (ssn) REFERENCES Employees
ON DELETE NO ACTION)
ENGINE = InnoDB:
Syntax error close to:

ON DELETE NO ACTION)
ENGINE = InnoDB

If you change your statement to:

CREATE TABLE Dept_Mgr ( 
    did INTEGER,
    dname CHAR(20),
    ssn CHAR(11) NOT NULL,
    PRIMARY KEY (did),
    FOREIGN KEY (ssn) REFERENCES Employees(ssn)
) engine = innodb;

it does work.


You only have the foreign key referencing the table, not the column.

Try: references Employee.ssn

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号