create primary and foreign key relationship

百般思念 提交于 2019-12-04 01:46:47

问题


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;

回答1:


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;


来源:https://stackoverflow.com/questions/32323196/create-primary-and-foreign-key-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!