1) db와 table 생성
CREATE database fk;
use fk;
CREATE table user (
ui Int PRIMARY key AUTO_INCREMENT,
name varchar(20) NOT null
);
create table income (
ii int primary key auto_increment,
amount int not null,
ui int,
FOREIGN KEY (ui) REFERENCES user(ui)
);
2) 데이터 추가
insert into user(name)
values ('A'),('B'),('C');
insert into income(amount, ui)
values (100,1),(200,2), (500,3), (700,1), (400,1);
3) foreign KEY 로 연결되어 있는 것을 추가해보기
INSERt into income (amount, ui) values (100,4);
DELETE from user WHERE ui = 1 LIMIT 1;
4) foreign key 삭제
ALTER TABEL income DROP FOREIGN KEY fk_user;
/* income table의 fk_user 컬럼을 추가해주는데
이는 user table에 있는 ui 값을 외래 키로 가지고 올것.
그리고 update는 cascade를 이용하고, delete는 set null 설정값을 이용해라 */
alter table income ADD constraint fk_user
foreign key(ui) references user(ui)
on update cascade on DELETE set null;
set null
no action
set default
restrict