【问题标题】:How to fix "Failed to add the foreign key constraint. Missing index for constraint 'transactions_ibfk_1' in the referenced table 'account'"如何修复“添加外键约束失败。在引用的表‘account’中缺少约束‘transactions_ibfk_1’的索引”
【发布时间】:2019-02-06 14:57:15
【问题描述】:

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

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

【问题讨论】:

  • 索引表事务中的“account_id”字段并尝试
  • 你运行的是哪个版本的mysql?

标签: mysql sql


【解决方案1】:

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

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-07
    • 2019-02-27
    • 2017-09-16
    • 2016-05-23
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多