데이터베이스 DB/MySQL

[MySQL/3일차] 키, 제약조건

하나비 HANABI 2023. 1. 26. 11:11

기본키

-- 기본키 지정
create table newcustomer (
custid int primary key,
name varchar(40),
address varchar(40),
phone varchar(30)
);

 

복합키

가격에는 default값인 10000과, 2000보다 커야 한다는 제약조건 지정

-- 복합키 지정
create table newbook (
bookname varchar(20) not null,
publisher varchar(20) unique,
price integer default 10000 check(price>2000),
primary key(bookname, publisher)
);

-- price에는 디폴드값인 10000이 자동으로 들어감
insert into newbook (bookname, publisher) values('BBB', 'bbb');

 

외래키

cascade: 부모 테이블에 적용된 명령어(delete, update 등)을 자식 테이블에도 적용

create table neworders (
orderid int,
custid int not null,
saleprice int,
orderdate date,
primary key (orderid),
foreign key (custid) references newcustomer(custid) on delete cascade
);

부모 테이블의 데이터가 삭제되는 경우 자식 테이블의 데이터 연쇄 삭제.

newcustomer 테이블에서 2번 회원을 지우면, neworders 테이블에서도 2번회원의 기록이 사라짐.

delete from newcustomer where custid=2;

 

제약조건 (NOT NULL, 기본키) 추가

/* 컬럼 생성 */
alter table newbook
add bookid integer;

/* 데이터값이 null이면 기본키로 지정이 불가! 먼저 값을 넣어준다 */
update newbook set bookid=1 where bookname='축구 아는 여자';
update newbook set bookid=2 where bookname='축구의 역사';
update newbook set bookid=3 where bookname='축구의 이해';

/* not null 제약조건 추가 및 기본키 지정까지 한번에 */
ALTER TABLE newbook
CHANGE COLUMN bookid bookid INT NOT NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (bookname, publisher, bookid);
;

 

Error Code 3730 : 외래키로 인한 테이블 삭제 불가

-- 테이블 삭제 시 외래키를 체크하지 않도록 설정
SET foreign_key_checks = 0;

-- 테이블 삭제
DROP TABLE newcustomer;

-- 삭제 후 다시 외래키를 체크하도록 설정
SET foreign_key_checks = 1;