[DB] Foreign Key 해제, 추가

그냥·2022년 7월 7일
0

db

목록 보기
3/3

DB를 만지다 보면 Foreign Key를 해제하거나 설정해야되는 일이 생긴다. 그런 일을 대비해서 쿼리문으로 Foreign Key를 해제하고 설정하는 방법에 대해서 알아보고자 한다.



1. Foreign Key 해제

1) 테이블 constraint name 확인

쿼리문

select * from information_schema.table_constraints where table_name = '테이블명';

response

+--------------------+-------------------+---------------------------------------+--------------+------------+-----------------+----------+
| CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME                       | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE | ENFORCED |
+--------------------+-------------------+---------------------------------------+--------------+------------+-----------------+----------+
| def                | greeneeds         | pk_uri                                | greeneeds    | projects   | UNIQUE          | YES      |
| def                | greeneeds         | projects_user_id_155ff78a_fk_users_id | greeneeds    | projects   | FOREIGN KEY     | YES      |
+--------------------+-------------------+---------------------------------------+--------------+------------+-----------------+----------+
  • projects 테이블에 걸려있는 필요한 Foreign Key의 constraint_name을 확인한다.

    constraint_name = projects_user_id_155ff78a_fk_users_id


1) 테이블 Foreign Key 해제

쿼리문

alter table [테이블명] drop foreign key [제약조건명]; 

예시

alter table projects drop foreign key projects_user_id_155ff78a_fk_users_id; 



2. Foreign Key 추가

쿼리문

alter table [추가할테이블명] add constraint [constraint_name] foreign key(컬럼명) references [부모테이블명] (PK컬럼명) 

예시

alter table projects add constraint projects_user_id_155ff78a_fk_users_id foreign key

0개의 댓글