◆ Foreign Key (외래키)
페이지 정보
본문
[설명]
01. 외래키 (Foreign Key)란?
외래키는 두 테이블을 서로 연결하는 데 사용되는 키이다.
외래키가 포함된 테이블을 자식 테이블이라고 하고 외래키 값을 제공하는 테이블을 부모 테이블이라한다.
02. 외래키 사용시 주의 사항
1) 외래키 값은 NULL이거나 부모 테이블의 기본키 값과 동일해야한다. (참조 무결성 제약조건)
2) 부모 테이블의 기본키, 고유키를 이용해서 외래키로 지정할 수 있다.
아래 notice (부모 테이블)와 comment (자식 테이블) 가 있다.
외래키를 가진 테이블이 자식 테이블이고, 참조되는 테이블이 부모 테이블이다.
create table notice (
uid int auto_increment primary key,
id varchar(20) not null,
name varchar(20) not null,
subject varchar(255) default '',
content text
);
create table comment (
uid int auto_increment primary key,
notice_uid int not null,
id varchar(20) not null,
name varchar(20) not null,
subject varchar(255) not null
);
ALTER TABLE comment ADD FOREIGN KEY (notice_uid) REFERENCES notice(uid); //외래키 적용
insert into notice values (null,'1111','일돌이','제목','내용');
insert into notice values (null,'2222','이순이','제목2','내용2');
insert into comment values (null,'1','3333','삼돌이','한줄댓글');
[삭제를 통해 확인해보자]
delete from notice where uid=1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`comment`, CONSTRAINT `comment_ibfk_1` FOREIGN KEY (`notice_uid`) REFERENCES `notice` (`uid`))
delete from notice where uid=2;
Query OK, 1 row affected (0.01 sec)
delete from comment where uid=1;
Query OK, 1 row affected (0.01 sec)
delete from notice where uid=1;
Query OK, 1 row affected (0.01 sec)
기본 구조
CONSTRAINT [CONSTRAINT_NAME] FOREIGN KEY (자식 테이블 컬럼 명) REFERENCES 참조테이블(부모 테이블 기본키명) ON UPDATE 옵션 ON DELETE 옵션;
# CONSTRAINT [CONSTRAINT_NAME]은 생략이 가능하다.
select * from information_schema.table_constraints;
select * from information_schema.table_constraints where table_schema = 'test';
select * from information_schema.table_constraints where table_schema = 'test' and TABLE_NAME = 'comment';
# 외래키 삭제
ALTER TABLE comment DROP FOREIGN KEY comment_ibfk_1;
test)
insert into notice values (null,'1111','일돌이','제목','내용');
insert into comment values (null,'3','3333','삼돌이','한줄댓글');
delete from notice where uid=3; //삭제 가능
- 이전글● 테이블 구조와 데이터 복사 24.01.29
- 다음글mariaDB 11.1.2 다운로드 및 설치 23.12.23
댓글목록
등록된 댓글이 없습니다.