◆ Foreign Key (외래키) > MYSQL

본문 바로가기
사이트 내 전체검색

MYSQL

◆ Foreign Key (외래키)

페이지 정보

profile_image
작성자 관리자
댓글 0건 조회 169회 작성일 24-01-29 14:43

본문

[설명]


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; //삭제 가능


추천0 비추천0

댓글목록

등록된 댓글이 없습니다.

회원로그인

회원가입

사이트 정보

공지사항
자유게시판
질문답변
1:1문의

 

별명 : 터푸가위
주소 : 부산시 동래구 명장로20번길 90
대표 : 박규태
메일 : dancepkt@******.com

접속자집계

오늘
254
어제
217
최대
10,760
전체
276,001
Copyright © dancePKT . All rights reserved.