[22/04/03] Mysql 복습(3) 제약조건

Que Lin·2022년 4월 3일
0

1day 1commit

목록 보기
56/63

🔑제약조건

  • primary key : 고유한 데이터를 갖는 값 not null, unique 포함된 제약조건
  • foreign key : 2개의 테이블의 연관관계를 지정하는 조건, 참조하고자 하는 값의 pk를 지정함
  • unique : 특별한 값
  • not null : 값이 없으면 안되는 조건

제약조건 사용

create table 테이블 변수 값 (

컬럼명 타입 (크기),

컬럼명1 타입(크기)

constraint 제약조건 제약변수명 (제약을 지정할 컬럼)

)

  • 제약 조건 조회하기
select * from information_schema.table_constraints;
  • 제약 조건 특정 테이블 조회하기
select * from information_schema.table_constraints where table_name = 'trainee2';

제약조건 오류

  • error code 1048 column 't_id' cannot be null

  • error code 1062 : duplicate entry '20' for key 'trainee2.nk_trainee2'

테이블을 삭제하면 제약조건도 삭제됨

  • 제약조건 개별 삭제
    alter : 테이블 구조 변경, 이름변경, 타입, 크기 변경 등을 할때
alter table trainee2 drop constraint nk_trainee2;
  • pk 제약조건 삭제
alter table trainee2 drop primary key;
  • 테이블을 만들고 나서 제약 조건을 추가하는 경우
alter table trainee2 add constraint primary key(t_id);

alter table trainee2 add constraint unique un_new_trainee2(t_age);
  • 제약조건 이름을 주지 않는 경우
alter table trainee2 add constraint unique (t_email);

참조형 제약조건 foreign key

  • 만들기
create table e(

e1 int,

e2 varchar(10)

constraint primary key (e1)

);

create table f(

f1 int,

f2 varchar(20)

e1 int, - - 웬만하면 참조하는 변수와 같은 변수로 만들어준다.

constraint foreign key (e1) references e(e1)

);

삭제하기

1. 테이블 삭제하기

drop table e;(x) 먼저 참조하고 있는 f테이블 먼저 지워줘야 함.

drop table f; → drop table e;

2. 데이터 삭제 하기

  • 부모 자식 둘다 삭제(f(f1)도 삭제)
constraint foreign key (e1) references e(e1) on delete cascade;

delete from e where e1=3;
  • 참조한 데이터값이 null이 됨(e(e1) = null)
constraint foreign key (e1) references e(e1) on delete set null;

delete from e where e1=3;

수정 쿼리

- e테이블의 데이터2라는 값을 데이터234로 수정
- update e set e2='데이터234' where e1=2;
- update 테이블 set 컬럼=변경할데이터 where pk컬럼=값;
- mapper에 데이터 넣을 때 mysql에서 구문을 써본 후 스프링에 쓰기!
profile
1일 1커밋 1일 1벨로그!

0개의 댓글