· 7 years ago · Feb 07, 2019, 08:28 PM
1CREATE TABLE IF NOT EXISTS persons (
2 id SERIAL UNIQUE PRIMARY KEY,
3 name TEXT NOT NULL,
4 age INT NOT NULL
5);
6
7CREATE TABLE IF NOT EXISTS things (
8 id SERIAL UNIQUE PRIMARY KEY,
9 name TEXT NOT NULL,
10 bought_on TIMESTAMP
11);
12
13CREATE TABLE IF NOT EXISTS persons_things (
14 person_id INT NOT NULL REFERENCES persons(id),
15 thing_id INT NOT NULL REFERENCES things(id),
16 PRIMARY KEY (person_id, thing_id)
17);
18
19INSERT INTO persons (name, age) VALUES
20('Spiderman', 20),
21('Ironman', 40),
22('Doctor Strange', 44);
23
24INSERT INTO things (name, bought_on) VALUES
25('mask', now()),
26('armor', NULL),
27('cape', NULL);
28
29INSERT INTO persons_things (person_id, thing_id) VALUES
30(1, 1),
31(2, 1),
32(2, 2),
33(3, 3);
34
35ERROR: insert or update on table "persons_things" violates foreign key constraint "persons_things_person_id_fkey"
36DETAIL: Key (person_id)=(0) is not present in table "persons".
37STATEMENT: insert into "persons_things" ("person_id", "thing_id") values ($1, $2)