外键引用同一个表中的主键Mysql

时间:2018-06-11 10:34:04

标签: mysql sql phpmyadmin foreign-keys primary-key

# Sql to create userdetails table:
CREATE TABLE `userdetails` (
 `user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
 `user_group_id` int(1) unsigned NOT NULL,
 `name` varchar(50) NOT NULL,
 `email_id` varchar(50),
 `password` varchar(50) NOT NULL,
 `mobile_no` varchar(10) NOT NULL,
 `company_id` int(3) unsigned,
 `vehicle_id` varchar(10),
 `date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `date_updated` datetime NOT NULL,
 `created_by` int(3) unsigned NOT NULL,
 `status` enum('0','1') NOT NULL DEFAULT '0',
 PRIMARY KEY (`user_details_id`),
 UNIQUE KEY `email_id` (`email_id`),
 FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
 FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
 FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

关注'user_details_id'和'created_by'列,当created_by未引用现有的user_details_id时,就会出现冲突。

意思是,如果我使用所需的详细信息创建自己的配置文件,我的user_details_id尚未生成,因此我不知道输入到created_by字段的值(理想情况下应该包含我的user_details_id)。 / p>

如果有人能够指导我如何处理这样的冲突,并且如果有一种方法可以确定user_details_id字段的值在甚至生成之前可能是什么,我将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:0)

您无法通过设置服务器变量foreign_key_checks暂时禁用外键检查来处理它

SET FOREIGN_KEY_CHECKS=0;

INSERT INTO cities userdetails(....);

SET FOREIGN_KEY_CHECKS = 1;

答案 1 :(得分:0)

# Sql to create userdetails table:
CREATE TABLE `userdetails` (
 `user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
 `user_group_id` int(1) unsigned NOT NULL,
 `name` varchar(50) NOT NULL,
 `email_id` varchar(50),
 `password` varchar(50) NOT NULL,
 `mobile_no` varchar(10) NOT NULL,
 `company_id` int(3) unsigned,
 `vehicle_id` varchar(10),
 `date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `date_updated` datetime NOT NULL,
 `created_by` int(3) unsigned,
 `status` enum('0','1') NOT NULL DEFAULT '0',
 PRIMARY KEY (`user_details_id`),
 UNIQUE KEY `email_id` (`email_id`),
 FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
 FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
 FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

允许created_by接受NULL值似乎是对此问题的快速解决方法,因为这可能意味着用户是自行创建的。