product_type 테이블과 product 테이블 생성
CREATE TABLE product_type(
name VARCHAR(30) NOT NULL,
id SERIAL PRIMARY KEY
);
product_type 테이블은 상품의 카테고리를 의미합니다.
CREATE TABLE product(
type_id INTEGER REFERENCES product_type(id),
name VARCHAR(30) NOT NULL,
supplier VARCHAR(30) NOT NULL,
description TEXT NOT NULL,
id SERIAL PRIMARY KEY
);
product 테이블에서 type_id는 product_type.id를 참조합니다.
product_type (1) ────< product (N)
하나의 product_type에 여러 개의 product가 속할 수 있습니다.
즉, 하나의 상품 분류에 여러 상품이 속할 수 있습니다.
예를 들어보겠습니다.
product_type
INSERT INTO product_type(name) VALUES('Business');
INSERT INTO product_type(name) VALUES('Casual');
INSERT INTO product_type(name) VALUES('Athletic');

product
INSERT INTO product VALUES
(1, 'Grandview', 'Allen Edmonds', 'Classic broguing adds texture to a charming longwing derby crafted in America from lustrous leather'),
(1, 'Clarkston', 'Allen Edmonds', 'Sharp broguing touches up a charming, American-made derby fashioned from finely textured leather'),
(2, 'Venetian Loafer', 'Mezlan', 'Suede upper, leather sole'),
(2, 'Malek', 'Johnston & Murphy', 'Contrast insets at the toe and sides bring updated attitude to a retro-inspired sneaker set on a sporty foam sole and triangle-lugged tread.'),
(3, 'Air Max 270 React', 'Nike', 'The reggae inspired Nike Air 270 React fuses forest green with shades of tan to reveal your righteous spirit'),
(3, 'Joyride', 'Nike', 'Tiny foam beads underfoot conform to your foot for cushioning that stands up to your mileage'),
...
그래서 이 두 테이블은 이렇게 연결됩니다.
| product.name | product_type.name |
|---|---|
| Grandview | Business (1) |
| Clarkston | Business (1) |
| Venetian Loafer | Casual (2) |
| Malek | Casual (2) |
| Air Max 270 React | Athletic (3) |
| Joyride | Athletic (3) |
Business 타입에는 Grandview 제품과 Clarkston 제품 2개가 연결되어 있습니다.
즉, 하나의 상품 분류에 여러 개의 상품이 속할 수 있습니다.
product_type에는 현재 Business (1), Casual (2), Athletic (3)만 존재합니다.
만약 product 테이블에 155라는 type_id를 집어넣어본다면?
INSERT INTO product(type_id, name, supplier, description)
VALUES (155, 'Air Force', 'Nike', 'The Nike Air Force 1 (AF1) is a classic sneaker, originally a basketball shoe designed by Bruce Kilgore')
product_type에는 3까지 존재하고, 155라는 값이 없기 때문에,
이런 오류가 뜹니다.
ERROR: "product" 테이블에서 자료 추가, 갱신 작업이 "product_type_id_fkey" 참조키(foreign key) 제약 조건을 위배했습니다
(type_id)=(155) 키가 "product_type" 테이블에 없습니다.
오류: "product" 테이블에서 자료 추가, 갱신 작업이 "product_type_id_fkey" 참조키(foreign key) 제약 조건을 위배했습니다
SQL state: 23503
Detail: (type_id)=(155) 키가 "product_type" 테이블에 없습니다.