Data Analysis/혼공SQL

[혼공SQL] 5-1 테이블 만들기

알밤바 2022. 8. 3. 09:03
728x90
반응형

본 포스팅은 '한빛출판네트워크'의 '혼공SQL' 책을 기반으로 작성한 포스팅입니다.

 

데이터베이스와 테이블 설계하기

1) 회원테이블(member)

  • 아이디(mem_id) : 기본 키(primary key / PK)
  • 평균 키(height) : TINYINT UNSIGNED → 0~ 255 범위
  • UNSIGNED 예약어 (4-1 MySQL의 데이터 형식)

2) 구매테이블(buy)

  • 순번(num) : 1, 2, 3, … 자동 입력하도록 설정
  • 아이디(mem_id) : 외래 키(Foreign Key / FK)
  • **AUTO_INCREMENT (**3-3. 데이터 변경을 위한 SQL문)


1. 테이블 생성하기

  • 데이터 베이스 생성
-- 데이터베이스(naver_db) 생성
DROP DATABASE IF EXISTS naver_db;
create database naver_db;

 

  • 회원 테이블 (member) 생성
-- 회원 테이블(member) 생성
use naver_db;
drop table if exists member;
create table member
( mem_id     char(8)      not null   primary key,
  mem_name   varchar(10)  not null,
  mem_number tinyint      not null,
  addr       char(2)      not null,
  phone1     char(3)      null,
  phone2     char(8)      null,
  height     tinyint unsigned null,
  debut_date date             null
  );
  

 

  • 구매 테이블 (buy) 생성
  -- 구매 테이블(buy) 생성
  drop table if exists buy;
  create table buy
  ( num        int auto_increment   not null   primary key,
    mem_id     char(8)              not null,
    prod_name  char(6)              not null,
    group_name char(4)              null,
    price      int unsigned         not null,
    amount     smallint unsigned    not null,
		**foreign key(mem_id) references member(mem_id)**
    );
  • 외래키 설정
    • 테이블을 만들 때 제일 마지막에 FOREIGN KEY 예약어로 지정
    • 참조하는 테이블에도 동일한 컬럼이 있어야 함
    • foreign key(mem_id) references member(mem_id)

 

2. 데이터 입력하기

-- 회원 테이블(member)
insert into member values('TWC', '트와이스', 9, '서울', '02', '11111111', 167, '2015-10-19');
insert into member values('BLK', '블랙핑크', 4, '경남', '055', '22222222', 163, '2016-8-8');
insert into member values('WMN', '여자친구', 6, '경기', '031', '33333333', 166, '2015-1-15');

-- 구매 테이블(buy)
insert into buy values(null, 'BLK', '지갑', null, 30, 2);
insert into buy values(null, 'BLK', '맥북프로', '디지털', 1000, 1);
insert into buy values(null, 'APN', '아이폰', '디지털', 200, 1);   -- member 테이블에 'APN' 데이터가 없기에 오류 발생

 

3. 데이터 출력

select * from member;

select * from buy;

 

728x90
반응형