Modelleer 1:N-relaties met foreign keys

Introductie tot relationele databases in SQL

Timo Grossenbacher

Data Journalist

Het huidige databasemodel

Introductie tot relationele databases in SQL

Het volgende databasemodel

Introductie tot relationele databases in SQL

Relaties implementeren met foreign keys

  • Een foreign key (FK) verwijst naar de primary key (PK) van een andere tabel
  • Domein van FK moet gelijk zijn aan domein van PK
  • Elke FK-waarde moet bestaan in de PK van de andere tabel (FK-constraint of "referentiële integriteit")
  • FKs zijn geen echte sleutels
Introductie tot relationele databases in SQL

Een query

SELECT * FROM professors LIMIT 8;
 id |    firstname    |  lastname   | university_s..
  --+-----------------+-------------+-------------
  1 | Karl            | Aberer      | EPF
  2 | Reza Shokrollah | Abhari      | ETH
  3 | Georges         | Abou Jaoudé | EPF
  4 | Hugues          | Abriel      | UBE
  5 | Daniel          | Aebersold   | UBE
  6 | Marcelo         | Aebi        | ULA
  7 | Christoph       | Aebi        | UBE
  8 | Patrick         | Aebischer   | EPF
SELECT * FROM universities;
 id  |   university   | university_city
<hr />--+----------------+-----------------
 EPF | ETH Lausanne   | Lausanne
 ETH | ETH Zürich     | Zurich
 UBA | Uni Basel      | Basel
 UBE | Uni Bern       | Bern
 UFR | Uni Freiburg   | Fribourg
 UGE | Uni Genf       | Geneva
 ULA | Uni Lausanne   | Lausanne
 UNE | Uni Neuenburg  | Neuchâtel
 USG | Uni St. Gallen | Saint Gallen
 USI | USI Lugano     | Lugano
 UZH | Uni Zürich     | Zurich
Introductie tot relationele databases in SQL

Foreign keys opgeven

CREATE TABLE manufacturers (
 name varchar(255) PRIMARY KEY);

INSERT INTO manufacturers 
VALUES ('Ford'), ('VW'), ('GM');

CREATE TABLE cars ( model varchar(255) PRIMARY KEY, manufacturer_name varchar(255) REFERENCES manufacturers (name)); INSERT INTO cars VALUES ('Ranger', 'Ford'), ('Beetle', 'VW');
-- Geeft een fout!
INSERT INTO cars 
VALUES ('Tundra', 'Toyota');
Introductie tot relationele databases in SQL

Foreign keys toevoegen aan bestaande tabellen

ALTER TABLE a 
ADD CONSTRAINT a_fkey FOREIGN KEY (b_id) REFERENCES b (id);
Introductie tot relationele databases in SQL

Laten we dit implementeren!

Introductie tot relationele databases in SQL

Preparing Video For Download...