我想将外键添加到名为“ katalog”的表中。
ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
当我尝试执行此操作时,出现以下错误消息:
Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
INNODB状态错误:
120405 14:02:57表mytable的外键约束错误。#sql-7fb1_7d3a:
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
当我使用此查询时,它可以工作,但是执行“删除时”操作错误:
ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
两个表都是InnoDB,两个字段都是“ INT(11)not null”。我正在使用MySQL 5.1.61。尝试在MacBook Pro上使用MySQL Workbench(最新)触发此ALTER Query。
表创建语句:
CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$
CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Bezeichnung` varchar(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
katalog
有int(11) unsigned
。sprache
没有该usigned
部分,因此两列不相同。
auto_increment
列,这很不好。此外,MySQL手册说:Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
。因此,是的,数据类型相似且符号相同。
SHOW CREATE TABLE
,所以我只能问-列名是否真的是ID,大写?