我正在尝试实现this,但我得到一个循环或多个级联路径,无法查看问题所在以及如何解决问题。
CREATE TABLE Staff(
Id INT NOT NULL PRIMARY KEY
)
CREATE TABLE Supevision (
SupervisorId INT NOT NULL FOREIGN KEY REFERENCES Staff(Id) ON UPDATE CASCADE ON DELETE CASCADE,
SupervisedId INT NOT NULL FOREIGN KEY REFERENCES Staff(Id) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (SupervisorId, SupervisedId)
)
答案 0 :(得分:1)
试试这个:
表:员工
CREATE TABLE IF NOT EXISTS `staff` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(15) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT
表:超级视觉
CREATE TABLE IF NOT EXISTS `supevision` (
`details_id` int(5) NOT NULL AUTO_INCREMENT,
`SupervisorId` int(5) NOT NULL,
`SupervisedId` int(5) NOT NULL,
`is` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`details_id`),
KEY `SupervisorId` (`SupervisorId`),
KEY `SupervisedId` (`SupervisedId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT
查询:
ALTER TABLE `supevision`
ADD CONSTRAINT `supevision_ibfk_2` FOREIGN KEY (`SupervisedId`) REFERENCES `staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `supevision_ibfk_1` FOREIGN KEY (`SupervisorId`) REFERENCES `staff` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
答案 1 :(得分:0)
您可以删除其中一个外部约束,但可以用触发器替换它。
DROP TABLE Supevision
DROP TABLE Staff
CREATE TABLE Staff(
Id INT NOT NULL PRIMARY KEY
)
GO
CREATE TABLE Supevision (
SupervisorId INT NOT NULL FOREIGN KEY REFERENCES Staff(Id) ON UPDATE CASCADE ON DELETE CASCADE,
SupervisedId INT NOT NULL --FOREIGN KEY REFERENCES Staff(Id) ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (SupervisorId, SupervisedId)
)
GO
CREATE TRIGGER DELETEStuff
ON Staff
FOR DELETE
AS
BEGIN
DELETE sv
FROM deleted d
INNER JOIN Supevision sv
ON d.Id = sv.SupervisedId
DELETE sv
FROM deleted d
INNER JOIN Supevision sv
ON d.Id = sv.SupervisorId
END
GO
CREATE TRIGGER UPDATEStuff
ON Staff
FOR UPDATE
AS
BEGIN
UPDATE Supevision
SET SupervisedId = inserted.id
FROM inserted, deleted
WHERE Supevision.SupervisedId = deleted.Id
UPDATE Supevision
SET SupervisorId = inserted.id
FROM inserted, deleted
WHERE Supevision.SupervisorId = deleted.Id
END
GO
INSERT INTO Staff (ID)
VALUES (1), (2), (3), (4), (5), (6), (7)
INSERT INTO Supevision (SupervisorId, SupervisedId)
VALUES (1, 2), (2, 3), (3, 4), (5, 6), (6, 7)
DELETE FROM Staff WHERE ID = 3
UPDATE Staff SET Id = 60 WHERE Id=6
SELECT * FROM Supevision
SELECT * FROM Staff