Oracle
 sql >> Datenbank >  >> RDS >> Oracle

SQL-Fehler „Übergeordneter Schlüssel nicht gefunden“ für falsch verwendete Fremdschlüssel?

Leider (für Ihren DDL-Code) muss ich @William Robertson zustimmen - Sie müssen Ihr Modell ändern und müssen daher Ihren DDL-Code vollständig überarbeiten. Gründe dafür sind wie folgt:

Wenn wir uns ein rückentwickeltes Modell aus Ihrem ursprünglichen DDL-Code ansehen, können wir sehen, dass REQUISITION 3 (sorry, 4) übergeordnete Tabellen hat. Aus diesem Grund schlagen seine Einfügungen aufgrund von Fremdschlüsselverletzungen immer fehl. Ihr Modell:

Ein vereinfachtes Beispiel, das das Problem in Form von DDL-Code veranschaulicht, könnte etwa so aussehen:

create table parent1 ( id number primary key ) ; -- analogy: supplies_pharmaceutical
create table parent2 ( id number primary key ) ; -- analogy: supplies_nonsurgical
create table parent3 ( id number primary key ) ; -- analogy: supplies_surgical

create table child ( -- analogy: requisitions
  id number primary key
, parentid number 
);

alter table child add constraint fkey_parent1
foreign key ( parentid ) references parent1 ( id ) ;

alter table child add constraint fkey_parent2
foreign key ( parentid ) references parent2 ( id ) ;

alter table child add constraint fkey_parent3
foreign key ( parentid ) references parent3 ( id ) ;

begin
  insert into parent1 ( id ) values ( 1 ) ;
  insert into parent2 ( id ) values ( 2 ) ;
  insert into parent3 ( id ) values ( 3 ) ;
end ;
/

Also, wenn unsere übergeordneten Tabellen gefüllt sind, nur eine kurze Überprüfung:

select 'parent1 (id) -> ' || id from parent1
union all
select 'parent2 (id) -> ' ||  id from parent2
union all
select 'parent3 (id) -> ' ||  id from parent3
;

-- result
'PARENT1(ID)->'||ID  
parent1 (id) -> 1    
parent2 (id) -> 2    
parent3 (id) -> 3 

Alles gut. Jetzt wollen wir einige Zeilen in unsere untergeordnete Tabelle einfügen.

insert into child ( id, parentid ) values ( 100, 1 ) ;
-- ORA-02291: integrity constraint (...FKEY_PARENT3) violated - parent key not found

insert into child ( id, parentid ) values ( 101, 2 ) ;
-- ORA-02291: integrity constraint (...FKEY_PARENT3) violated - parent key not found

insert into child ( id, parentid ) values ( 102, 3 ) ;
-- ORA-02291: integrity constraint (...FKEY_PARENT2) violated - parent key not found

Sie sehen, dass die richtige übergeordnete Tabelle nicht einfach "automatisch ausgewählt" wird.

In Williams Modell OTOH hat REQUISITION nur einen Elternteil (Tabelle) in Bezug auf "Vorräte". Das sollte das Einfügen von Zeilen viel einfacher machen ... siehe unten.