无法在 MySQL 中创建递归关系

Can't create a recursive relationship in MySQL

我需要一些帮助,我正在尝试使用下面的代码创建递归关系,但一直出现错误

CREATE TABLE `Employee` (
  `SSN` int,
  `address` varchar(50),
  `salary` varchar(50),
  `sex` varchar(50),
  `birthDate` varchar(50),
  `dependantId` int,
  `supervisorId` int,
  PRIMARY KEY (`SSN`),
  FOREIGN KEY (`dependantId`) REFERENCES `Dependant`(`dependantId`),
  FOREIGN KEY (`supervisorId`) REFERENCES `Employee`(`supervisorId`)
);

这是我遇到的错误: #1005 - 无法创建 table company recursive.employee(错误号:150“外键约束格式不正确”)

table 需要一个 ID 列才能被外键约束“引用”。该列必须是 UNIQUE,最好也是 NOT NULL。典型的解决方案如下所示:

CREATE TABLE Employee (
  `SSN` int,
  `address` varchar(50),
  `salary` varchar(50),
  `sex` varchar(50),
  `birthDate` varchar(50),
  id int not null unique, -- non nullable unique (acts as a key)
  dependantId int, -- nullable reference
  supervisorId int, -- nullable reference
  PRIMARY KEY (`SSN`),
  FOREIGN KEY (dependantId) REFERENCES Employee (id),
  FOREIGN KEY (supervisorId) REFERENCES Employee (id)
);

在这种情况下 dependantIdsupervisorId 可以为 null 并成为指向相同 table Employee.

的引用

作为旁注,通常层次结构只包括对主管的引用,而不包括对依赖者的引用。在你的情况下,后者有点多余,如果主管有多个家属,则效果不佳。

引用应该转到 SSN,因为它是主键

所以你会得到

CREATE TABLE `Employee` (
  `SSN` int,
  `address` varchar(50),
  `salary` varchar(50),
  `sex` varchar(50),
  `birthDate` varchar(50),
  `dependantId` int,
  `supervisorId` int,
  PRIMARY KEY (`SSN`),
  FOREIGN KEY (`dependantId`) REFERENCES `Employee`(`SSN`),
  FOREIGN KEY (`supervisorId`) REFERENCES `Employee`(`SSN`)
);
INSERT INTO Employee VALUES (1,'adreess1','10', 'male', '2000-01-01',NULL,NULL)
INSERT INTO Employee VALUES (2,'adreess1','10', 'male', '2000-01-01',NULL,1)
INSERT INTO Employee VALUES (3,'adreess1','10', 'male', '2000-01-01',2,1)
SELECT * FROM Employee
SSN | address  | salary | sex  | birthDate  | dependantId | supervisorId
--: | :------- | :----- | :--- | :--------- | ----------: | -----------:
  1 | adreess1 | 10     | male | 2000-01-01 |        null |         null
  2 | adreess1 | 10     | male | 2000-01-01 |        null |            1
  3 | adreess1 | 10     | male | 2000-01-01 |           2 |            1

db<>fiddle here