
이제 슬슬 어려워지고있다...자바의 부모자식관계가 차라리 더 쉬운 것 같이 느껴진다.
1. 참조제약 조건
참조제약 조건은 외래키, 참조키라고도 부른다.(FK) 부모 테이블이 있어야 관계설정이 가능하다.
1) 테이블을 만들면서 생성하는 방법
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
-- 부모
create table parent_table(
user_id varchar(30) primary key
,user_name varchar(20)
,user_phone varchar(20)
,user_addr varchar(100)
);
-- 자식
create table child_table(
order_id int(10) primary key
,user_id varchar(30)
,price int(8)
,qty int(5)
);
|
cs |
자식 테이블에서 user_id를 키로 가져다 쓰긴 했는데 기본 키(primary key)로 사용하지는 않았다.
2) 테이블을 만든 후 생성하는 방법
ALTER TABLE [테이블 이름] ADD CONSTRAINT [제약조건 종류]([적용할 컬럼]) REFERENCES [부모테이블 명]([가져올 컬럼])
|
1
|
alter table child_table add constraint foreign key(user_id) references parent_table(user_id);
|
cs |
위의 두 커리는 부모의 키를 자식이 기본키로 사용하고 있지 않기 때문에 '비식별 관계'이다.
3) 식별관계 추가
아래의 경우는 본인의 기본키이면서 부모로부터 가져온 외래키이기 때문에 '식별관계'이다.
|
1
2
3
4
5
|
create table iden_table(
user_id varchar(30) primary key
,etc varchar(100)
,constraint foreign key(user_id) references parent_table(user_id)
);
|
cs |

엔티티 관계도를 통해 테이블간의 관계를 확인 할 수 있다.
parent_table과 child_table은 비식별관계이기 때문에 점선으로, parent_table과 iden_table은 식별관계이기 때문에 실선으로 표현되었다.
식별관계는 함부로 사용하지 않는 것이 좋다.
2. 연계 참조 무결성 제약조건
연계 참조는 부모자식 관계를, 무결성은 논리적으로 앞뒤가 맞는 것을 의미한다.
즉 연계 참조 무결성 제약조건은 부모자식간에 논리적으로 말이 맞지 않는 상황을 제약하는 것이며
부모없는 자식이 발생했을 경우 이것을 해결하는 것이라고 할 수 있다.
예를 들어 부모와 자식을 선언한 뒤 부모 데이터를 지워보자.
우선 부모와 자식을 선언해준 뒤, 각 테이블에 데이터를 넣어준다.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
-- 부모
create table test_parent(
supplier_id int(10) primary key
,supplier_name varchar(50) not null
,phone varchar(12)
);
-- 자식
create table test_child(
product_id int(10) primary key
,supplier_id int(10)
,product_price int(10)
,foreign key (supplier_id) references test_parent(supplier_id)
);
-- 각 부모 테이블과 자식 테이블에 데이터 넣기
insert into test_parent(supplier_id,supplier_name,phone)values(1,'김철수','02-123-1234');
insert into test_parent(supplier_id,supplier_name,phone)values(2,'홍길동','032-568-0078');
insert into test_parent(supplier_id,supplier_name,phone)values(3,'박영수','042-323-3234');
select * from test_parent tp;
insert into test_child(product_id,supplier_id,product_price)values(1111,1,6000);
insert into test_child(product_id,supplier_id,product_price)values(1112,2,7000);
insert into test_child(product_id,supplier_id,product_price)values(1113,3,8000);
select * from test_child tc;
|
cs |
이제 여기서 부모 데이터를 지워보겠다.
|
1
|
delete from test_parent where supplier_id = 1;
|
cs |

이 경우 에러가 뜨는 것을 확인할 수 있는데, 부모 데이터는 자식이 있는 상태에서는 삭제할 수 없기 때문이다.
이러한 에러를 해결하기 위해서는 자식을 먼저 지우고 부모를 지우는 방법(but 부모자식 관계가 복잡하면 힘들다)과
연계 참조 무결성 제약조건을 활용(ON DELETE CASCADE)하는 방법이 있다.