无法删除具有多个外键的数据

时间:2017-05-24 14:04:40

标签: sql

这些是我的表格:

CREATE TABLE COACH (
  COACH_ID  VARCHAR(8),
  COACH_NAME    VARCHAR(50),
  COACH_ADD VARCHAR(100),
  COACH_PHONENO CHAR(12),
  PRIMARY KEY (COACH_ID));

CREATE TABLE TEAM (
  TEAM_ID       VARCHAR(8),
  COACH_ID  VARCHAR(8),
  TEAM_NAME VARCHAR(50),
  TEAM_COLOUR   VARCHAR(10),
  PRIMARY KEY (TEAM_ID),
  CONSTRAINT TEAM_COACH_ID_FK 
  FOREIGN KEY (COACH_ID) REFERENCES COACH);

CREATE TABLE PARTICIPANT (
  PART_ID       VARCHAR(8),
  TEAM_ID       VARCHAR(8),
  SPORT_NAME    VARCHAR(15),
  PART_NAME VARCHAR(50),
  PART_IC       VARCHAR(14),
  PART_PHONENO  CHAR(12),
  PRIMARY KEY (PART_ID),
  CONSTRAINT SPORT_TEAM_ID_FK
  FOREIGN KEY (SPORT_NAME) REFERENCES SPORT,
  CONSTRAINT TEAM_TEAM_ID_FK
  FOREIGN KEY (TEAM_ID) REFERENCES TEAM );

这是我的SQL:

DELETE FROM TEAM 
WHERE TEAM_COLOUR='Magenta';

代码生成此错误:

  

错误报告:
  SQL错误:ORA-02292:违反完整性约束(HR.TEAM_TEAM_ID_FK) - 找到子记录
  02292. 00000 - “违反完整性约束(%s。%s) - 发现子记录”
  *原因:尝试删除具有外部依赖项的父键值。       *操作:先删除依赖项,然后删除父项或禁用约束。

我想要DELETE TEAM_COLOUR = 'MAGENTA'

2 个答案:

答案 0 :(得分:0)

首先删除所有Team_Colour =' Magenta'成员的成员。

然后您就可以删除团队了。

答案 1 :(得分:0)

也许是这样的:

语法有效:仍然不确定这对你来说是否适合你......

但要警告;级联删除可能很危险。如果您意外删除了一个团队,那么您也会丢失所有参与者信息......这就是为什么许多人更喜欢做两个删除语句。

ALTER TABLE PARTICIPANT
  DROP CONSTRAINT TEAM_TEAM_ID_FK;

ALTER TABLE PARTICIPANT
  ADD CONSTRAINT TEAM_TEAM_ID_FK
  FOREIGN KEY (TEAM_ID) 
  REFERENCES TEAM(TEAM_ID) 
  ON DELETE CASCADE;

然后

DELETE FROM TEAM WHERE TEAM_COLOUR='Magenta';

应该有效。

这是整个剧本:

CREATE TABLE COACH (
  COACH_ID  VARCHAR(8),
  COACH_NAME    VARCHAR(50),
  COACH_ADD VARCHAR(100),
  COACH_PHONENO CHAR(12),
  PRIMARY KEY (COACH_ID));

CREATE TABLE TEAM (
  TEAM_ID       VARCHAR(8),
  COACH_ID  VARCHAR(8),
  TEAM_NAME VARCHAR(50),
  TEAM_COLOUR   VARCHAR(10),
  PRIMARY KEY (TEAM_ID),
  CONSTRAINT TEAM_COACH_ID_FK 
  FOREIGN KEY (COACH_ID) REFERENCES COACH);

CREATE TABLE PARTICIPANT (
  PART_ID       VARCHAR(8),
  TEAM_ID       VARCHAR(8),
  SPORT_NAME    VARCHAR(15),
  PART_NAME VARCHAR(50),
  PART_IC       VARCHAR(14),
  PART_PHONENO  CHAR(12),
  PRIMARY KEY (PART_ID),
  CONSTRAINT TEAM_TEAM_ID_FK
  FOREIGN KEY (TEAM_ID) REFERENCES TEAM );

  insert into coach values (1,'Test1',NULL,NULL);
  Insert into Team values (1,1,'Test1','Blue');
  insert into team values (2,1,'Test1','Magenta');
  Insert into Participant (part_ID, Team_ID) values (1,1);
  Insert into Participant (part_ID, Team_ID) values (2,1);
  Insert into Participant (part_ID, Team_ID) values (3,2);

ALTER TABLE PARTICIPANT DROP Constraint TEAM_TEAM_ID_FK;

ALTER TABLE PARTICIPANT
  ADD CONSTRAINT TEAM_TEAM_ID_FK
  FOREIGN KEY (TEAM_ID) 
  REFERENCES TEAM(TEAM_ID) 
  ON DELETE CASCADE;
  DELETE FROM TEAM WHERE TEAM_COLOUR='Magenta';