MySQL数据库"创建表"询问

时间:2015-11-19 21:00:27

标签: mysql

CREATE TABLE `test`.`friendlist` (
  `Lid` INT NOT NULL,
  `Pid` INT NOT NULL,
  `Fid` INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Fid`),
  INDEX `Pid_idx` (`Pid` ASC),
  INDEX `Lid_idx` (`Lid` ASC, `Pid` ASC),
  CONSTRAINT `Lid`
    FOREIGN KEY (`Lid` , `Pid`)
    REFERENCES `test`.`loginauthentication` (`Lid` , `Pid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `Pid`
    FOREIGN KEY (`Pid`)
    REFERENCES `test`.`person` (`Pid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);

操作失败:将SQL脚本应用于数据库时出错。 错误1215:无法添加外键约束 SQL语句:

2 个答案:

答案 0 :(得分:1)

我尝试执行你的SQL,我发现 pid 列存在于表 loginauthentication 中,但我添加了列并再次运行你的SQL并且它有效!

ALTER TABLE `loginauthentication`ADD COLUMN `Pid`  int(11) NULL AFTER `Lid`

[SQL] CREATE TABLE  `friendlist` (
  `Lid` INT NOT NULL,
  `Pid` INT NOT NULL,
  `Fid` INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Fid`),
  INDEX `Pid_idx` (`Pid` ASC),
  INDEX `Lid_idx` (`Lid` ASC, `Pid` ASC),
  CONSTRAINT `Lid`
    FOREIGN KEY (`Lid` , `Pid`)
    REFERENCES `loginauthentication` (`Lid` , `Pid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `Pid`
    FOREIGN KEY (`Pid`)
    REFERENCES `person` (`Pid`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION);
Affected rows: 0
Time: 0.179ms

素不相识!

答案 1 :(得分:-1)

首先运行此DDL:

set foreign_key_checks=0;

然后进行查询

CREATE TABLE test.friendlist ( 
Lid INT NOT NULL,
  Pid INT NOT NULL,
  Fid INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 INDEX Pid_idx (Pid ASC),
 INDEX Lid_idx (Lid ASC, Pid ASC),
 CONSTRAINT Lid FOREIGN KEY (Lid , Pid) REFERENCES test.loginauthentication (Lid , Pid) ON DELETE NO ACTION ON UPDATE NO ACTION, 
CONSTRAINT Pid FOREIGN KEY (Pid) REFERENCES test.person (Pid) ON DELETE NO ACTION ON UPDATE NO ACTION);

EX:用我自己的参考表相应修改

mysql> show create table friendlistl

| friendlist | CREATE TABLE `friendlist` (
  `Lid` int(11) NOT NULL,
  `Pid` int(11) NOT NULL,
  `Fid` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`Fid`),
  KEY `Pid_idx` (`Pid`),
  KEY `Lid_idx` (`Lid`,`Pid`),
  CONSTRAINT `Lid` FOREIGN KEY (`Lid`, `Pid`) REFERENCES `test` (`Lid`, `Pid`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `Pid` FOREIGN KEY (`Pid`) REFERENCES `test` (`idn`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |