✍️ primary key = 기본 키
- 테이블의 각 레코드를 식별
- 중복되지 않는 고유값 포함
- NULL값 포함할 수 없음
- 테이블 당 하나의 기본키를 가짐
- 컬럼 하나 & 여러개 컬럼을 하나의 기본키로 지정 가능
01) 테이블 생성 시 기본키 지정해주는 방법
CREATE TABLE tablename
(
col1 datatype NOT NULL,
col2 datatype NOT NULL,
...
# constraint 생략 가능
CONSTRAINT constraint_name
PRIMARY KEY (col1, col2,...)
);
테이블에 primary key 삭제 & 추가하기
alter table person
drop primary key;
alter table person
add primary key (pid);
여러 개의 컬럼을 기본키로 지정하는 경우
alter table person
add constraint pk_person primary key (pid, name);
- constraint : 제약, 제한 뜻 (생략 가능) (생략 시 자동 생성됨)
- pk_person : person 테이블의 primary key라고 지정
✍️foreign key = 외래키
- 테이블과 테이블을 연결해주는 키
- 외래키로 지정된 컬럼은 연결된 테이블의 기본키(단일키)가 됨.
CREATE TABLE tablename
(
col1 datatype NOT NULL,
col2 datatype NOT NULL,
col3 datatype,
col4 datatype,
...
CONSTRAINT constraint_name
PRIMARY KEY (col1, col2,...)
CONSTRAINT constraint_name
FOREIGN KEY (col1, col2,...) REFERENCES REF_tablename(REF_colmun)
);
🚨 외래키는 참조 테이블 필요함!
01) 테이블 생성 시 (constraint 포함)
create table orders
(
oid int not null,
order_no varchar(16),
pid int,
primary key (oid),
constraint FK_person foreign key (pid) references person(pid)
);
person 참조 컬럼이 key에 외래키 (MUL) 표시가 되는 것을 알 수 있음.
02) 테이블 생성 시 (constraint 생략)
create table job
(
jid int not null,
name varchar(16),
pid int,
primary key (jid),
foreign key (pid) references person(pid)
);
한 테이블이 여러 개의 foreign key로 여러 개의 테이블을 참조할 수 있음!
✍️ constraint는 생략해도 자동 생성됨.
show create table tablename;
🚨 constraint 정보, foreign key 정보가 입력되어 있음
alter table orders
drop foreign key FK_person;
pid 외래키라고 기록되어 있지만
✍️ constraint와 foreign 정보가 없는 걸로 보아 참조 연결을 잘 삭제가 되었음.
alter table tablename
add foreign key (column) references REF_tablename(REF_column);
alter table orders
add foreign key (pid) references person(pid);