简体   繁体   中英

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. 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. Example I wanted the SSN to be 123456789, and I tried entering Super_SSN as 987654321. But I got FK constraint error. When I entered the same value for SSN and Super_SSN, it accepted it. 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. Please help me with this!

SuperSSN has to refer to the SSN of an existing employee.

You should enter the employees in a correct order - in your example SSN 987654321 first, then SSN 123456789 with SuperSSN = 987654321.

Or enter all employees without specifying SuperSSN and update it to correct values in another command.

You are getting the error because that FK is part of a recursive relationship. It means that an employee is related with another employee. If the second employee does not exist, then the FK constraint error appears. That's why you don't get an error when adding the same SSN. Posible solution: You can add a Super_SSN column as a simple field but not as a FK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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