Oracle
 SQL >> Database >  >> RDS >> Oracle

Garantire integrità tra tabelle correlate ma non collegate

Puoi ottenere l'integrità con ridondanza controllata e chiavi esterne composite. La tabella offr aggiunge una chiave univoca composta:

CREATE TABLE offr (
  offr_id INT NOT NULL,
  coy_id INT NOT NULL,
  PRIMARY KEY (offr_id),
  FOREIGN KEY (coy_id) REFERENCES ins_coy (coy_id),
  UNIQUE KEY (offr_id, coy_id)
);

La tabella provide usa una primary key composta:

CREATE TABLE provide (
  coy_id INT NOT NULL,
  type_id INT NOT NULL,
  PRIMARY KEY (coy_id, type_id),
  FOREIGN KEY (coy_id) REFERENCES ins_coy (coy_id)
);

La tabella subscribe usa due foreign key composite sovrapposte:

CREATE TABLE subscribe (
  naf_no INT NOT NULL,
  coy_id INT NOT NULL,
  type_id INT NOT NULL,
  PRIMARY KEY (naf_no, type_id),
  FOREIGN KEY (naf_no, coy_id) REFERENCES offr (offr_id, coy_id),
  FOREIGN KEY (coy_id, type_id) REFERENCES provide (coy_id, type_id)
);

Così un agente può sottoscrivere solo prodotti offerti dalla compagnia in cui è registrato. coy_id è ridondante ma necessario per garantire l'integrità.

In alternativa, puoi usare un trigger che verifica la relazione tramite join interni.