I have a problem that I am not sure how to solve correctly. My current design consists of two tables. employee and employee_management. My RDBMS is MySQL.
employee:
CREATE TABLE `employee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
employee_management:
CREATE TABLE `employee_management` (
`manager_id` int(11) NOT NULL,
`employee_id` int(11) NOT NULL,
UNIQUE INDEX `association` (`manager_id`,`employee_id`),
FOREIGN KEY (`manager_id`)
REFERENCES employee(id)
ON UPDATE CASCADE ON DELETE RESTRICT,
FOREIGN KEY (`employee_id`)
REFERENCES employee(id)
ON UPDATE CASCADE ON DELETE RESTRICT
)
Test data:
INSERT INTO employee(name) VALUES(
'Bob Smith'
)
INSERT INTO employee(name) VALUES(
'Bill Smith'
)
INSERT INTO employee_management(manager_id, employee_id) VALUES(
1,2
)
INSERT INTO employee_management(manager_id, employee_id) VALUES(
2,1
)
Selecting the rows from employee_management shows this:
+------------+-------------+
| manager_id | employee_id |
+------------+-------------+
| 2 | 1 |
| 1 | 2 |
+------------+-------------+
The rows returned indicate that Bill Smith manages Bob Smith, and Bob Smith manages Bill Smith which I believe is a circular reference. Two people managing each other doesn't make sense. I thought that the UNIQUE INDEX would prevent the insertion of rows that had any existing combination of values, but that did not work. I know I can prevent this from happening at the application level, but I'm not sure if that is the appropriate thing to do, but is this something that has to be enforced at the application level, or is there something I can do to prevent a circular reference? Managers should not also have managers.