试图创建一个外键,并保持收到此消息:
错误代码:1822无法添加外键约束。在引用表“帐户”缺少约束'transactions_ibfk_1人指数
很新的编程和SQL一般很抱歉,如果这是简单的。
CREATE DATABASE IF NOT EXISTS bank;
USE bank;
CREATE TABLE IF NOT EXISTS account
(
account_id int primary key auto_increment,
balance double,
type varchar(30),
date_opened datetime,
status varchar(30)
);
CREATE TABLE IF NOT EXISTS transactions
(
transaction_id int primary key auto_increment,
date_time datetime,
amount double,
remaining_balance double,
account_id int
);
alter table transactions
add foreign key(account_id)
references account(account_id)
on delete cascade
on update cascade;
我觉得外键的名称应该是不同的。最后一个部分即建立外键,尝试下面的代码片段
ALTER TABLE `bank`.`transactions`
ADD INDEX `fk_account_id_idx` (`account_id` ASC);
ALTER TABLE `bank`.`transactions`
ADD CONSTRAINT `fk_account_id`
FOREIGN KEY (`account_id`)
REFERENCES `bank`.`account` (`account_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;