Joining Relational Data between Tables in SQL
February 24, 2015
Grundlagen zu Keys und Relationen zwischen Tabellen.
Keys
- PRIMARY KEY: eindeutig, nicht NULL
- UNIQUE: eindeutig, kann NULL
- FOREIGN KEY: Referenz auf anderen PK
Beispiel: Genres
code
CREATE TABLE genres (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL UNIQUE
);
Foreign Key in movies
code
ALTER TABLE movies
ADD COLUMN genre_id INT,
ADD CONSTRAINT fk_movies_genre
FOREIGN KEY (genre_id) REFERENCES genres(id);
Werte setzen
code
UPDATE movies SET genre_id = 1 WHERE id IN (8, 9);