I am trying to create a table name accounts
. I have created a visual diagram in mysql workbench
. I copied sql command
from diagram try to create real table from my command line but command line is showing
ERROR 1215 (HY000): Cannot add foreign key constraint
Here is the query
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
The customers table could look like the below. It needs to have a common data type and index for the column in Parent table (customers). The FK will fail on child table create if column types / index are wrong.
And for an ALTER TABLE add constraint
command with pre-existing data in child, it will fail if data is not valid.
By the way, the INT(4) is just a display width. It is still an int.
create table customers(
customer_id int auto_increment primary key,
customerName varchar(100) not null
-- other columns
);
CREATE TABLE accounts(
account_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;