티스토리 뷰


주문(orders) 테이블과 주문 상세(order_details) 테이블을 분리하여 설계한 이유는?
=> 데이터베이스 정규화 원칙에 기반한 것
정규화는 데이터베이스 설계에서 중요한 과정으로, 데이터 중복을 최소화하고, 데이터 무결성을 향상시키며,
수정, 삽입, 삭제 등의 데이터베이스 작업 시 발생할 수 있는 문제점들을 방지하기 위해 사용됩니다.
주문과 주문 상세 테이블 분리의 목적
중복 제거: 주문 정보와 주문 상세 정보를 하나의 테이블로 관리할 경우, 주문 정보(예: 주문자 ID, 주문 날짜)가 각 주문 상품마다 반복적으로 저장됩니다. 이는 데이터 중복을 초래하고, 디스크 공간을 불필요하게 사용하게 합니다.
<코드 예시>
create table User(
id int primary key auto_increment,
username varchar(50) not null,
email varchar(100) not null unique,
password varchar(255) not null,
address varchar(255),
created_at timestamp default current_timestamp
);
create table Product(
id int primary key auto_increment,
name varchar(100) not null,
description text,
price decimal(10, 2) not null,
stock int default 0,
created_at timestamp default current_timestamp
);
create table `Order`(
id int primary key auto_increment, -- 주문 ID(PK)
user_id int not null, -- 주문한 고객의 ID(FK)
total_price decimal(10, 2) not null, -- 총 주문 금액
created_at timestamp default current_timestamp, -- 주문 시간
foreign key(user_id) references User(id)
);
create table Order_detail(
id int primary key auto_increment, -- 주문 상세 고유 ID(PK)
order_id int not null, -- 주문 ID(FK)
product_id int not null, -- 주문한 상품 ID(FK)
count int not null, -- 주문 수량
price decimal(10, 2) not null, -- 상품의 주문 가격
foreign key(order_id) references `Order`(id),
foreign key(product_id) references Product(id)
);
'MySQL' 카테고리의 다른 글
쇼핑몰과 카테고리 1단계, 2단계 (0) | 2024.06.12 |
---|---|
블로그 서비스의 DB 구축 (0) | 2024.06.11 |
self join (0) | 2024.06.11 |
정규화(1단계) (0) | 2024.06.11 |
DML, DDL, DCL이란 (0) | 2024.06.10 |