๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - foreign key์˜ on delete cascade ์„ค์ •๋ฐฉ๋ฒ•๊ณผ ๋™์ž‘ ๋ฐฉ๋ฒ• ๋ณธ๋ฌธ

๐Ÿ›ข๏ธDB/MySQL

[DB] ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค MySQL - foreign key์˜ on delete cascade ์„ค์ •๋ฐฉ๋ฒ•๊ณผ ๋™์ž‘ ๋ฐฉ๋ฒ•

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 12. 4. 11:49
๋ฐ˜์‘ํ˜•

MySQL์—์„œ ON DELETE CASCADE๋Š”
์™ธ๋ž˜ ํ‚ค(foreign key) ์ œ์•ฝ ์กฐ๊ฑด์—์„œ ์‚ฌ์šฉ๋˜๋Š” ์˜ต์…˜ ์ค‘ ํ•˜๋‚˜์ด๋‹ค.

์ด ์„ค์ •์„ ์‚ฌ์šฉํ•˜๋ฉด ์ฐธ์กฐํ•˜๋Š” ํ…Œ์ด๋ธ”์—์„œ ํ–‰์„ ์‚ญ์ œํ•  ๋•Œ,
ํ•ด๋‹น ํ–‰์„ ์ฐธ์กฐํ•˜๋Š” ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”์˜ ๊ด€๋ จ๋œ ํ–‰๋„ ์ž๋™์œผ๋กœ ์‚ญ์ œ๋œ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด, USER ํ…Œ์ด๋ธ”๊ณผ PHOTOS ํ…Œ์ด๋ธ”์ด ์žˆ๊ณ ,
PHOTOS  ํ…Œ์ด๋ธ”์˜ ์™ธ๋ž˜ ํ‚ค๊ฐ€ USER ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•ด๋ณด์ž.


USER  ํ…Œ์ด๋ธ”์˜ ํ–‰์ด ์‚ญ์ œ๋˜๋ฉด, ์ด์™€ ์—ฐ๊ด€๋œ PHOTOS ํ…Œ์ด๋ธ”์˜ ํ–‰๋„ ์ž๋™์œผ๋กœ ์‚ญ์ œ๋œ๋‹ค.

foreign key์˜
on delete cascade ์„ค์ •๋ฐฉ๋ฒ•

1. ์™ธ๋ž˜ ํ‚ค(foreign key)  ์„ค์ •

ํ•ด๋‹น ํ…Œ์ด๋ธ” ์„ค์ •์— ๋“ค์–ด๊ฐ€์„œ Foreign Key๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜๋ฉด์„œ
Foreign Key Options - on Delete : ๋ฅผ CASCADE๋กœ ์„ ํƒํ•œ๋‹ค.

 

 

2. index ์‹œํŠธ์—์„œ foreign ํ‚ค ์ƒ์„ฑ๋œ ๊ฒƒ์„ ํ™•์ธ

 

3. USER ํ…Œ์ด๋ธ”์—์„œ id 2๋ฒˆ์„ ์‚ญ์ œํ•˜๋ฉด
PHOTOS ํ…Œ์ด๋ธ” ์—์„œ๋„ user_id = 2๊ฐ€ ์‚ญ์ œ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

delete from users
where id = 2;

select * from users;
select *
from photos
where user_id = 2;

CASCADE ๋™์ž‘๋ฐฉ๋ฒ• ์ •๋ฆฌ

  • A ํ…Œ์ด๋ธ”์—์„œ ํ–‰์ด ์‚ญ์ œ๋˜๋ฉด,
    ํ•ด๋‹น ํ–‰์„ ์ฐธ์กฐํ•˜๋Š” B ํ…Œ์ด๋ธ”์˜ ํ–‰๋„ ์ž๋™์œผ๋กœ ์‚ญ์ œ๋œ๋‹ค.
  • ๋งŒ์•ฝ ์‚ญ์ œํ•˜๋ ค๋Š” A ํ…Œ์ด๋ธ”์˜ ํ–‰์„ ์ฐธ์กฐํ•˜๋Š” B ํ…Œ์ด๋ธ”์˜ ํ–‰์ด ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด,
    ์•„๋ฌด๋Ÿฐ ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค.

 

 

 

๋ฐ˜์‘ํ˜•