如何解决“无法添加外键约束。在引用表'account'中缺少约束'transactions_ibfk_1'的索引”

时间:2019-02-06 04:56:30

标签: mysql sql

尝试创建外键并不断收到此消息:

  

错误代码: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;

1 个答案:

答案 0 :(得分:0)

我认为外键的名称应该不同。 对于最后一部分,即创建外键,请尝试以下代码段

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;