创建主键和外键关系
create primary and foreign key relationship
我正在尝试创建一个 table 名称 accounts
。我在 mysql workbench
中创建了一个可视化图表。我从图中复制了 sql command
尝试从我的命令行创建真实的 table 但命令行显示
ERROR 1215 (HY000): Cannot add foreign key constraint
这里是查询
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;
客户 table 可能如下所示。 Parent table (customers) 中的列需要有通用数据类型和索引。如果列类型/索引错误,FK 将在子 table 创建时失败。
并且对于一个 ALTER TABLE add constraint
子命令中已经存在的数据,如果数据无效,它将失败。
顺便说一下,INT(4) 只是一个显示宽度。它仍然是一个整数。
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;
我正在尝试创建一个 table 名称 accounts
。我在 mysql workbench
中创建了一个可视化图表。我从图中复制了 sql command
尝试从我的命令行创建真实的 table 但命令行显示
ERROR 1215 (HY000): Cannot add foreign key constraint
这里是查询
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;
客户 table 可能如下所示。 Parent table (customers) 中的列需要有通用数据类型和索引。如果列类型/索引错误,FK 将在子 table 创建时失败。
并且对于一个 ALTER TABLE add constraint
子命令中已经存在的数据,如果数据无效,它将失败。
顺便说一下,INT(4) 只是一个显示宽度。它仍然是一个整数。
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;