#1005 - 无法创建表`agenceassurance` .operation`(错误:150"外键约束形成错误")

时间:2018-05-09 13:20:24

标签: mysql foreign-keys constraints create-table

错误:150"外键约束形成错误")

DROP DATABASE IF EXISTS AgenceAssurance;
CREATE DATABASE IF NOT EXISTS AgenceAssurance;
USE AgenceAssurance;

CREATE TABLE Logininfo (
  idLogin    INT(3)  PRIMARY KEY  NOT NULL AUTO_INCREMENT,
  userName       VARCHAR(50) NOT NULL,
  pass       VARCHAR(50),
  usertype   VARCHAR(50)          DEFAULT NULL,
  GrantedKey VARCHAR(8)           DEFAULT NULL
)ENGINE = InnoDB;

CREATE TABLE Operation (
  idOpt    INT PRIMARY KEY  NOT NULL AUTO_INCREMENT,
  libelOpt TEXT,
  dateOpt  DATETIME DEFAULT now(),
  userName VARCHAR(50),
   CONSTRAINT fk_login FOREIGN KEY (userName) REFERENCES Logininfo (userName)
)ENGINE = InnoDB;

错误 SQL查询:

CREATE TABLE Operation (
  idOpt    INT PRIMARY KEY  NOT NULL AUTO_INCREMENT,
  libelOpt TEXT,
  dateOpt  DATETIME DEFAULT now(),
  userName VARCHAR(50),
  CONSTRAINT fk_login FOREIGN KEY (userName) REFERENCES Logininfo (userName)
)ENGINE = InnoDB

MySQL说:

1005 - 无法创建表agenceassuranceoperation(错误:150"外键约束形成错误")(详情...)

2 个答案:

答案 0 :(得分:0)

CONSTRAINT pk_Log PRIMARY KEY(idLogin,userName): 尝试如下: CONSTRAINT pk_Log PRIMARY KEY(userName) 因为:一次两个字段用PK,不能用作FK。

答案 1 :(得分:0)

Logininfo 表中的字段 userName 必须为UNIQUE。您只能使用引用唯一字段的外键。

就像这样:

userName VARCHAR(50) NOT NULL UNIQUE