EDIT # 2:-
After following Spencer 7593's answer, i.e. creating the table without the foreign keys, and then adding them using the alter table
statement, the table was created successfully and the foreign keys were added successfully.
But now I wonder why? Why does it work when we create the table and then add the foreign key constraints using alter table
statement, and not when we do it all in the create table
statement?
I am creating the following tables in my database. The first two were created successfully but the third one is giving this error.
I checked my database for the points in this answer which I could understand. Please tell me why I am getting this error.
CREATE TABLE a (
a_id INT(255) NOT NULL AUTO_INCREMENT,
name VARCHAR(5000),
code VARCHAR(5000),
PRIMARY KEY (a_id)
);
CREATE TABLE b (
b_id INT(255) NOT NULL AUTO_INCREMENT,
b_name VARCHAR(5000),
PRIMARY KEY (b_id)
);
CREATE TABLE c ( -- error code 1005 can t create c errno 150 mysql
a_id INT(255), -- fk
b_id INT(255), -- fk
PRIMARY KEY (a_id, b_id),
FOREIGN KEY (a_id)
REFERENCES a (a_id),
FOREIGN KEY (b_id)
REFERENCES b(b_id)
);
EDIT:-
I executed just these three statements separately (after changing the size of all INT
types to 11
- thanks to the comment by Michael Berkowski), and to my surprise, it did create the tables, but gave this log (if I am using the right word):
3 4 01:03:49 CREATE TABLE a (
a_id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(5000),
code VARCHAR(5000),
PRIMARY KEY (a_id)
) 0 row(s) affected 0.156 sec
3 5 01:03:54 CREATE TABLE b (
b_id INT(11) NOT NULL AUTO_INCREMENT,
b_name VARCHAR(5000),
PRIMARY KEY (b_id)
) 0 row(s) affected 0.234 sec
3 6 01:03:58 CREATE TABLE c ( -- error code 1005 can t create c errno 150 mysql
a_id INT(11), -- fk
b_id INT(11), -- fk
PRIMARY KEY (a_id, b_id),
FOREIGN KEY (a_id)
REFERENCES a (a_id),
FOREIGN KEY (b_id)
REFERENCES b(b_id)
) 0 row(s) affected 0.203 sec
That is all the three tables are created, but an error is returned at the creation of the third table.
EDIT # 3:-
Output from SHOW CREATE TABLE a, and SHOW CREATE TABLE b:-
CREATE TABLE `a` (
`a_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(5000) DEFAULT NULL,
`code` varchar(5000) DEFAULT NULL,
PRIMARY KEY (`a_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `b` (
`b_id` int(11) NOT NULL AUTO_INCREMENT,
`b_name` varchar(5000) DEFAULT NULL,
PRIMARY KEY (`b_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8