我可以运行以下查询,并且结果的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;

最佳答案

错过了chat_group_users上未签名的人-

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

09-26 09:27