简体   繁体   English

sql中的同一表中的外键和主键

[英]Foreign key and primary key in same table in sql

I have a table employee in which PK is SSN and I want to make FK as Super_SSN which would refer to SSN. 我有一个表员工,其中PK是SSN,我想将FK设置为​​Super_SSN,这将引用SSN。 Before adding any data to my table, I was able to make Super_SSN as my FK, but I wasn't able to add data to Super_SSN other than the same value of SSN. 在将任何数据添加到表之前,我可以将Super_SSN设置为我的FK,但是除了相同的SSN值之外,我无法将数据添加到Super_SSN。 Example I wanted the SSN to be 123456789, and I tried entering Super_SSN as 987654321. But I got FK constraint error. 示例我希望SSN为123456789,并尝试输入Super_SSN为987654321。但是我收到FK约束错误。 When I entered the same value for SSN and Super_SSN, it accepted it. 当我为SSN和Super_SSN输入相同的值时,它接受了它。 Then, I removed the FK from Super_SSN and added data, after that I tried to add FK to Super_SSN, then I got error. 然后,我从Super_SSN中删除了FK并添加了数据,之后我尝试将FK添加到Super_SSN中,然后出现错误。 Please help me with this! 请在这件事上给予我帮助!

SuperSSN has to refer to the SSN of an existing employee. SuperSSN必须引用现有员工的SSN

You should enter the employees in a correct order - in your example SSN 987654321 first, then SSN 123456789 with SuperSSN = 987654321. 您应该以正确的顺序输入员工-在您的示例中,首先输入SSN 987654321,然后SuperSSN = 987654321的SSN 123456789。

Or enter all employees without specifying SuperSSN and update it to correct values in another command. 或者输入所有员工而不指定SuperSSN ,然后在另一个命令SuperSSN其更新为正确的值。

You are getting the error because that FK is part of a recursive relationship. 因为FK是递归关系的一部分,所以您会收到错误消息。 It means that an employee is related with another employee. 这意味着一个员工与另一个员工有关系。 If the second employee does not exist, then the FK constraint error appears. 如果第二个雇员不存在,则会出现FK约束错误。 That's why you don't get an error when adding the same SSN. 这就是为什么在添加相同的SSN时不会出现错误。 Posible solution: You can add a Super_SSN column as a simple field but not as a FK. 可能的解决方案:您可以将Super_SSN列添加为简单字段,但不能添加为FK。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM