简体   繁体   English

创建主外键关系

[英]create primary and foreign key relationship

I am trying to create a table name accounts .我正在尝试创建一个表名accounts I have created a visual diagram in mysql workbench .我在mysql workbench创建了一个可视化图表。 I copied sql command from diagram try to create real table from my command line but command line is showing我从图表中复制了sql command尝试从我的命令行创建真正的表,但命令行显示

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.如果列类型/索引错误,FK 将在创建子表时失败。

And for an ALTER TABLE add constraint command with pre-existing data in child, it will fail if data is not valid.对于在子项中具有预先存在的数据的ALTER TABLE add constraint命令,如果数据无效,它将失败。

By the way, the INT(4) is just a display width.顺便说一下,INT(4) 只是一个显示宽度。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM