0

当试图在父表上运行删除查询时,我被锁定了。以下是表结构,执行“DELETE FROM PARENT WHERE PARENT_ID = 1;”会造成死锁 -

------------------创建相关表--------------

CREATE TABLE PARENT (
    PARENT_ID INT NOT NULL,
    PARENT_NAME VARCHAR(100) NOT NULL
);
CREATE TABLE CHILD_ONE (
    CHILD_ONE_ID INT NOT NULL,
    CHILD_ONE_NAME VARCHAR(100) NOT NULL,
    SELF_REFERNCE_ID INT,
    LANGUAGE_ID INT NOT NULL
);
CREATE TABLE CHILD_TWO (
    CHILD_TWO_ID INT NOT NULL,
    CHILD_ONE_ID INT NOT NULL,
    QUANTITY INT,
    LANGUAGE_ID INT NOT NULL
);

------------------------在表上创建索引------------------------ ------

ALTER TABLE PARENT ADD CONSTRAINT PARENT_PK PRIMARY KEY (PARENT_ID);
ALTER TABLE CHILD_ONE ADD CONSTRAINT CHILD_ONE_PK PRIMARY KEY (CHILD_ONE_ID,LANGUAGE_ID);
ALTER TABLE CHILD_ONE ADD CONSTRAINT CHILD_ONE_ID_FK FOREIGN KEY (CHILD_ONE_ID) REFERENCES PARENT (PARENT_ID)
ON DELETE CASCADE;
ALTER TABLE CHILD_ONE ADD CONSTRAINT SELF_REFERNCE_ID_FK FOREIGN KEY (SELF_REFERNCE_ID) REFERENCES PARENT (PARENT_ID)
ON DELETE CASCADE;
ALTER TABLE CHILD_TWO ADD CONSTRAINT CHILD_TWO_PK PRIMARY KEY (CHILD_TWO_ID,LANGUAGE_ID);
ALTER TABLE CHILD_TWO ADD CONSTRAINT CHILD_TWO_ID_FK FOREIGN KEY (CHILD_TWO_ID) REFERENCES PARENT (PARENT_ID)
ON DELETE CASCADE;
ALTER TABLE CHILD_TWO ADD CONSTRAINT CHILD_ONE_ID_FK FOREIGN KEY (CHILD_ONE_ID) REFERENCES PARENT (PARENT_ID)
ON DELETE CASCADE;

------------------------------创建触发器表------ ------------

CREATE TRIGGER CHILD_ONE_TRIGGER AFTER DELETE ON CHILD_ONE 
REFERENCING OLD AS O FOR EACH ROW
DELETE FROM PARENT WHERE PARENT_ID = O.CHILD_ONE_ID;

CREATE TRIGGER CHILD_TWO_TRIGGER AFTER DELETE ON CHILD_TWO
REFERENCING OLD AS O FOR EACH ROW
DELETE FROM PARENT WHERE PARENT_ID = O.CHILD_TWO_ID;

---------------插入记录------------------ ------------

INSERT INTO PARENT (PARENT_ID, PARENT_NAME) VALUES (1,'CHILD_ONE-1');
INSERT INTO PARENT (PARENT_ID, PARENT_NAME) VALUES (2,'CHILD_ONE-2');
INSERT INTO PARENT (PARENT_ID, PARENT_NAME) VALUES (3,'CHILD_ONE-3');
INSERT INTO PARENT (PARENT_ID, PARENT_NAME) VALUES (4,'CHILD_TWO-1');
INSERT INTO PARENT (PARENT_ID, PARENT_NAME) VALUES (5,'CHILD_TWO-2');

INSERT INTO CHILD_ONE (CHILD_ONE_ID, CHILD_ONE_NAME, SELF_REFERNCE_ID, LANGUAGE_ID) VALUES (1,'CHILD_ONE-1', NULL, 1);
INSERT INTO CHILD_ONE (CHILD_ONE_ID, CHILD_ONE_NAME, SELF_REFERNCE_ID, LANGUAGE_ID) VALUES (1,'CHILD_ONE-1', NULL, 2);
INSERT INTO CHILD_ONE (CHILD_ONE_ID, CHILD_ONE_NAME, SELF_REFERNCE_ID, LANGUAGE_ID) VALUES (2,'CHILD_ONE-2', 1, 1 );
INSERT INTO CHILD_ONE (CHILD_ONE_ID, CHILD_ONE_NAME, SELF_REFERNCE_ID, LANGUAGE_ID) VALUES (3,'CHILD_ONE-3', 2, 2 );

INSERT INTO CHILD_TWO (CHILD_TWO_ID, CHILD_ONE_ID, QUANTITY, LANGUAGE_ID) VALUES (4, 1, 501, 1);
INSERT INTO CHILD_TWO (CHILD_TWO_ID, CHILD_ONE_ID, QUANTITY, LANGUAGE_ID) VALUES (5, 2, 501, 1);
COMMIT;
4

0 回答 0