Mysql 如何定义外键约束
我有三张mysql表。表已经创建Mysql 如何定义外键约束,mysql,Mysql,我有三张mysql表。表已经创建 Requests - request_id, request_message, user_id Responses - response_id, response_message, user_id users - user_id, user_name 现在我想在上面定义外键约束,比如 1. If user_id is not present in Users table, and someone is inserting the data in Re
Requests - request_id, request_message, user_id
Responses - response_id, response_message, user_id
users - user_id, user_name
现在我想在上面定义外键约束,比如
1. If user_id is not present in Users table, and someone is inserting the data in Requests or Responses for that user_id -- then error
2. If request_id is not present in Requests table, then if someone is inserting in responses table for that request_id -- then error
3. If someone deletes an user_id, all associated requests and responses with that user_id should be deleted automatically.
4. If someone deletes an request_id, all the associated responses with it, should be deleted automatically.
如果我遗漏了什么,请告诉我
如何实现这一功能
谢谢
Devesh以下是创建表的完整sql:
CREATE TABLE IF NOT EXISTS `reponses` (
`response_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`response_message` varchar(45) DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`response_id`,`user_id`),
KEY `fk_reponses_users1` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `requests` (
`request_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`request_message` varchar(45) DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`request_id`,`user_id`),
KEY `fk_requests_users` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=3 ;
ALTER TABLE `reponses`
ADD CONSTRAINT `reponses_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
ALTER TABLE `requests`
ADD CONSTRAINT `requests_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE NO ACTION;
允许您删除与用户相关的记录的选项是delete CASCADE上的。默认情况下,MySql设置了NO ACTION
,它指的是RESTRICT
,当父记录有相关对象时,不允许删除父记录。我想你没有提到回复和请求之间的关系,但你应该明白;)