我在MySQL数据库中的表中添加外键约束时遇到了一些问题。
我有以下用户表:
CREATE TABLE `user` (
`Id` varchar(128) NOT NULL,
`Email` varchar(255) NOT NULL,
`EmailConfirmed` tinyint(1) NOT NULL,
`PasswordHash` longtext,
`SecurityStamp` longtext,
`PhoneNumber` longtext,
`PhoneNumberConfirmed` tinyint(1) NOT NULL,
`TwoFactorEnabled` tinyint(1) NOT NULL,
`LockoutEndDateUtc` datetime DEFAULT NULL,
`LockoutEnabled` tinyint(1) NOT NULL,
`AccessFailedCount` int(11) NOT NULL,
`UserName` varchar(255) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1这是我的用户通知表,我试图添加一个外键到:
CREATE TABLE `usernotice` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`notifySitemap` bit(1) NOT NULL,
`notifyRobots` bit(1) NOT NULL,
`user_id` varchar(128) DEFAULT NULL,
`health_site_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `user_constraint_idx` (`user_id`),
KEY `healthSiteId_idx` (`health_site_id`),
CONSTRAINT `healthSiteId` FOREIGN KEY (`health_site_id`) REFERENCES `health_site` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8我试图在user.id列中引用usernotice.user_id列。为此,我使用以下SQL:
ALTER TABLE usernotice
ADD CONSTRAINT userId
FOREIGN KEY (user_id)
REFERENCES user (Id)
ON DELETE NO ACTION
ON UPDATE NO ACTION;当我执行这个命令时,我会得到一个1215代码的错误。有人能告诉我我做错了什么吗?
编辑:在检查了show create table查询之后,我注意到所使用的字符集有一个不同之处。用另一个图表集重新创建usernotice表,修复了这个问题。
发布于 2017-10-31 09:58:03
外键和引用键中的https://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html对应列必须具有类似的数据类型。整数类型的大小和符号必须相同。字符串类型的长度不一定相同。对于非二进制(字符)字符串列,字符集和排序规则必须相同。
你的字符集不一样..。
https://stackoverflow.com/questions/47031627
复制相似问题