我喜欢添加外键,这个表,但不行!如果我尝试新表不起作用,但其他旧表可用。有什么问题?
CREATE TABLE `tanora` (
`idtanora` int(11) NOT NULL,
`tema` varchar(250) NULL,
`megjegyzes` varchar(255) DEFAULT NULL,
`datum` date NOT NULL,
`osztaly` varchar(20) NOT NULL,
`megtartott` int(11) NOT NULL,
`targy` varchar(45) NOT NULL,
`kezdete` time NOT NULL,
`vege` time NOT NULL,
PRIMARY KEY (`idtanora`),
UNIQUE KEY `idtanora_UNIQUE` (`idtanora`),
KEY `osztazon_idx` (`osztaly`)
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci;
CREATE TABLE `osztaly` (
`osztalyazon` varchar(20) NOT NULL,
`osztalyfonokazon` varchar(11) NOT NULL,
`osztalynev` varchar(45) NOT NULL,
`indul` year(4) NOT NULL,
PRIMARY KEY (`osztalyazon`),
UNIQUE KEY `osztalyazon_UNIQUE` (`osztalyazon`),
KEY `ofazon_idx` (`osztalyfonokazon`),
CONSTRAINT `tanarazon01` FOREIGN KEY (`osztalyfonokazon`) REFERENCES `tanar` (`szemelyiszam`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci;
ERROR 1215: Cannot add foreign key constraint
SQL Statement:
ALTER TABLE `enaplo`.`tanora`
ADD CONSTRAINT `osztalyra`
FOREIGN KEY (`osztaly`)
REFERENCES `enaplo`.`osztaly` (`osztalyazon`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'tanora' already exists
SQL Statement:
CREATE TABLE `tanora` (
`idtanora` int(11) NOT NULL,
`tema` varchar(250) NOT NULL,
`megjegyzes` varchar(255) DEFAULT NULL,
`datum` date NOT NULL,
`osztaly` varchar(20) NOT NULL,
`megtartott` int(11) NOT NULL,
`targy` varchar(45) NOT NULL,
`kezdete` time NOT NULL,
`vege` time NOT NULL,
PRIMARY KEY (`idtanora`),
UNIQUE KEY `idtanora_UNIQUE` (`idtanora`)
) ENGINE=InnoDB DEFAULT CHARSET=latin2 COLLATE=latin2_hungarian_ci
foreign key (osztaly)
references enaplo.osztaly (osztalyazon)
on delete no action
on update no action:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables. See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
答案 0 :(得分:1)
确保您拥有一致的列定义:
在您的引用表osztaly
中,需要使用与osztalyfonokazon
表中引用字段应用的完全相同的特征来定义外键列tanar
。
目前,osztalyfonokazon
中的osztaly
定义如下:
`osztalyfonokazon` VARCHAR(11) NOT NULL
那么,然后在tanar
表中,szemelyiszam
定义应该看起来像
`szemelyiszam` VARCHAR(11) PRIMARY KEY
或
`szemelyiszam` VARCHAR(11) UNIQUE KEY NOT NULL
取决于您的需求。
无论哪种方式,请确保szemelyiszam
是 PRIMARY KEY
或至少 UNIQUE KEY
,声明为 {引用的NOT NULL
表中的{1}} 。
此外,MySQL要求对引用的列进行索引 出于性能原因。但是,系统不强制执行 要求引用的列为UNIQUE或声明为NOT 空值。处理对非唯一键或键的外键引用 对于诸如的操作,没有很好地定义包含NULL值的值 更新或删除CASCADE。建议您使用外键 仅引用UNIQUE(包括PRIMARY)和NOT NULL键。