0

我正在尝试实现这一点,但我得到了一个循环或多个级联路径,并且看不到问题出在哪里以及如何解决它。

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)
)
4

2 回答 2

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;
于 2013-06-25T08:20:52.283 回答
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 
于 2013-06-25T08:06:12.713 回答