我在尝试创建外键时不断收到错误1064:
ALTER TABLE `zajimavost`
ADD CONSTRAINT FK_zaj_bod
FOREIGN KEY def_bod
REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE;
它抱怨道:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE' at line 4
我在有或没有反引号的情况下尝试过,问题总是一样的。
我的桌子:
CREATE TABLE `zajimavost` (
`zaj_id` int(11) NOT NULL,
`lok_id` int(11) NOT NULL,
`nazev` varchar(255) COLLATE utf8_czech_ci NOT NULL,
`kategorie` int(11) NOT NULL DEFAULT '1',
`datace_od` int(11) NOT NULL DEFAULT '31',
`datace_do` int(11) NOT NULL DEFAULT '60',
`def_bod` int(11) DEFAULT NULL,
PRIMARY KEY (`zaj_id`),
KEY `ck_zaj_lok` (`lok_id`),
KEY `zaj_id` (`zaj_id`),
KEY `FK_zaj_kat` (`kategorie`),
KEY `FK_zaj_bod` (`def_bod`),
CONSTRAINT `FK_zaj_kat` FOREIGN KEY (`kategorie`) REFERENCES `kategorie` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_zaj_lok` FOREIGN KEY (`lok_id`) REFERENCES `lokalita` (`lok_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci
CREATE TABLE `bod` (
`gid` int(11) NOT NULL AUTO_INCREMENT,
`geom` point DEFAULT NULL,
`radius` int(4) NOT NULL DEFAULT '50',
PRIMARY KEY (`gid`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci
表格中有数据。
那么如何解决呢?
答案 0 :(得分:6)
在添加外键时,您需要在子表列名中使用()
,试试这个
ALTER TABLE zajimavost
ADD CONSTRAINT FK_zaj_bod
FOREIGN KEY (def_bod) REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE;