错误1005(105)无法创建表...但为什么?

时间:2013-02-05 22:16:45

标签: mysql sql foreign-keys

create table bankdb.customer(
    customer_name varchar(45) not null,
    social_security int not null,
    customer_street varchar(45),
    customer_city varchar(45),
primary key(`social_security`)
)engine=InnoDB;

create table bankdb.branch(
    branch_name varchar(45) not null,
    branch_city varchar(45),
    assets int,
primary key (`branch_name`)
)engine=InnoDB;

create table bankdb.account(
    branch_name varchar(45),
    account_number varchar(45) not null,
    balance int,
primary key (`account_number`),
constraint fk_acount_branch
    foreign key (`branch_name`)
    references bankdb.branch(`branch_name`)
)engine=InnoDB;  

create table bankdb.depositor(
    customer_name varchar(45) not null,
    account_number varchar(45) not null,
primary key (`customer_name`, `account_number`),
constraint fk_depositor_customer
    foreign key(`customer_name`)
    references bankdb.customer(`customer_name`),
constraint fk_depositor_account
    foreign key(`account_number`)
    references bankdb.account(`account_number`)
)engine=InnoDB;

那是我的sql代码...我得到错误无法为表bankdb.depositor创建表...我的外键有什么问题吗?有线索吗?

1 个答案:

答案 0 :(得分:2)

根据您的新脚本编辑,以下内容似乎在SQL Fiddle中有效。我不得不添加索引:

create table bankdb.customer(
    customer_name varchar(45) not null,
    social_security int not null,
    customer_street varchar(45),
    customer_city varchar(45),
  primary key(`social_security`),
  INDEX (customer_name)
)engine=InnoDB;

create table bankdb.branch(
    branch_name varchar(45) not null,
    branch_city varchar(45),
    assets int,
  primary key (`branch_name`)
)engine=InnoDB;

create table bankdb.account(
    branch_name varchar(45),
    account_number varchar(45) not null,
    balance int,
  primary key (`account_number`),
  INDEX (account_number),
  constraint fk_acount_branch
      foreign key (`branch_name`)
      references bankdb.branch(`branch_name`)
)engine=InnoDB;  

create table bankdb.depositor(
  customer_name varchar(45) not null,
  account_number varchar(45) not null,
  primary key (`customer_name`, `account_number`),
  INDEX (customer_name),  
  INDEX (account_number),
  constraint fk_depositor_customer
      foreign key(`customer_name`)
      references bankdb.customer(`customer_name`),
  constraint fk_depositor_account
      foreign key(`account_number`)
      references bankdb.account(`account_number`)
)engine=InnoDB;

请参阅SQL Fiddle with Demo

如果这是您的完整脚本,则问题在于account的创建表。

您正试图在branch表上创建一个似乎不存在的外键:

create table bankdb.account(
    branch_name varchar(45),
    account_number varchar(45) not null,
    balance int,
primary key (`account_number`),
constraint fk_acount_branch
    foreign key (`branch_name`)
    references bankdb.branch(`branch_name`)  -- does this exist
)engine=InnoDB;  

<击>