表格:
CREATE TABLE `relation` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`gender` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_relation` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `invite` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date_sent` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`relation_id` int(10) unsigned NOT NULL,
`email` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user` (`user_id`),
CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
执行的SQL语句是:
ALTER TABLE `invite`
ADD CONSTRAINT `fk_relation`
FOREIGN KEY (`relation_id`)
REFERENCES `relation` (`id`)
ON DELETE CASCADE ON UPDATE RESTRICT
Mysql错误:
SQLSTATE[HY000]: General error: 1005 Can't create table 'dbtest.#sql-d00_39' (errno: 121).
relation.id 和 invite.relation_id 列的类型相同int(10)unsigned
更新 添加此密钥时,表邀请为空。 表关系有3行。
答案 0 :(得分:1)
试试这个:
ALTER TABLE invite
ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id)
REFERENCES relation(id)
根据doc语法是正确的SQL FOREIGN KEY Constraint
答案 1 :(得分:0)
外键创建的DDL现在自动包含用于指定“删除”和“更新”操作的语句。但是,对于“删除”,它包含语句“ON DELETE RESTRICT”,它似乎不是有效的T-SQL语句。
尝试这个:
ALTER TABLE invite WITH CHECK ADD CONSTRAINT fk_relation FOREIGN KEY (relation_id) REFERENCES relation (id)