无法在mysql中应用外键约束

时间:2016-12-10 12:35:14

标签: mysql sql foreign-keys

我可以运行以下查询,结果中的user_id列中没有空值 -

select c.*,r.user_id from chat_group_users c left join roleuser r 
on c.user_id = r.user_id;

但我不能应用外键约束和mysql只是说

Error Code: 1215. Cannot add foreign key constraint

我写的命令 -

ALTER TABLE chat_group_users 
ADD CONSTRAINT fk_roleuser FOREIGN KEY (user_id) REFERENCES roleuser (user_id)
ON DELETE cascade  ON UPDATE cascade;

表格结构 -

CREATE TABLE `roleuser` (
`User_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserNM` varchar(50) NOT NULL,
`UserPS` varchar(150) NOT NULL,
`r_username` varchar(50) DEFAULT NULL,
`UGroup` varchar(5) NOT NULL DEFAULT 'Usar',
`FirstName` varchar(45) NOT NULL,
`LastName` varchar(45) NOT NULL,   
 PRIMARY KEY (`User_ID`),
 UNIQUE KEY `Index_2` (`UserNM`),
 ) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=latin1;


CREATE TABLE `chat_group_users` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) DEFAULT NULL,
`user_id` int(10) DEFAULT NULL,
`is_admin` varchar(5) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 PRIMARY KEY (`auto_id`),
 UNIQUE KEY `unique_user_group` (`user_id`,`group_id`),
 KEY `fc_group_id` (`group_id`),
 CONSTRAINT `fc_group_id` FOREIGN KEY (`group_id`) 
 REFERENCES `chat_group`(`auto_id`) 
 ON DELETE CASCADE ON UPDATE CASCADE
  )ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

1 个答案:

答案 0 :(得分:1)

错过了chat_group_users上的unsigned -

 `User_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, ...