以下创建语句失败
DROP TABLE IF EXISTS `book` ;
DROP TABLE IF EXISTS `person` ;
CREATE TABLE `person` (
`name` VARCHAR(30) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `book` (
`author` VARCHAR(30) NOT NULL,
`title` VARCHAR(100) NOT NULL,
PRIMARY KEY (`author`, `title`),
FOREIGN KEY (`author`)
REFERENCES `person` (`name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE = InnoDB ;
出现以下错误
ERROR 1215 (HY000): Cannot add foreign key constraint
并且所有数据类型和字段名称都是正确的。为什么外键约束失败?
答案 0 :(得分:1)
我找到了答案,DEFAULT CHARSET
条款不匹配。第二个create table语句还需要声明DEFAULT CHARSET
。
DROP TABLE IF EXISTS `book` ;
DROP TABLE IF EXISTS `person` ;
CREATE TABLE `person` (
`name` VARCHAR(30) NOT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `book` (
`author` VARCHAR(30) NOT NULL,
`title` VARCHAR(100) NOT NULL,
PRIMARY KEY (`author`, `title`),
FOREIGN KEY (`author`)
REFERENCES `person` (`name`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE = InnoDB DEFAULT CHARSET=latin1;