TIL

2024.08.19 foreign key

Gisungcu 2024. 8. 19. 22:50

 

 

MySQL :: MySQL 8.4 Reference Manual :: 1.7.2.3 FOREIGN KEY Constraint Differences

1.7.2.3 FOREIGN KEY Constraint Differences The MySQL implementation of foreign key constraints differs from the SQL standard in the following key respects: If there are several rows in the parent table with the same referenced key value, InnoDB performs a

dev.mysql.com

 

다는 못 읽었습니다. 

 

 

주변 사례를 보면 테이블에 외래키 제약조건을 걸지 않고 운영하는 경우가 있습니다.
이유는 무엇일까요. 
제약조건을 걸면 부모행이나 자식행에 s lock이 걸리는 경우가 많기 때문이라고 생각합니다.

-> 테스트 해보자.
어느 테이블이 서로 참조하는지 개발자가 인지하고 있다면 외래키 제약조건은 없어도 되겠지만..
휴먼에러는 일어날 수 있습니다.

 

외래키 검증은 언제 이뤄지는가?

설명에 보면 트랜잭션 커밋 시가 아닌! 바로 이뤄진다고 쓰여 있다. 일반적인 Sql  문법에서는 트랜잭션 커밋 시 이뤄진다는데 다른 db를 안 써봐서 모르겠다.

 

 

요즘 db공부를 계속하고있습니다.

예전에 docker를 몰랐을 때는 mysql 직접 깔고 oracle 직접 깔고 오류 뜨는, 삭제도 힘든 지옥을 맛봤었는데 docker가 참 편합니다.

 

 

CREATE TABLE parent (
    id INT,
    INDEX (id)
) ENGINE=InnoDB;

CREATE TABLE child (
    id INT,
    parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id)
        REFERENCES parent(id)
        ON DELETE RESTRICT
) ENGINE=InnoDB;

mysql> INSERT INTO parent (id)
    ->     VALUES ROW(1), ROW(2), ROW(3), ROW(1);
Query OK, 4 rows affected (0.02 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> INSERT INTO child (id,parent_id)
    ->     VALUES ROW(1,1), ROW(2,2), ROW(3,3);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> start transaction;
Query OK, 0 rows affected (0.00 sec)

mysql> DELETE FROM parent WHERE id=1;
ERROR 1451 (23000): Cannot delete or update a parent row: a
foreign key constraint fails (`sample`.`child`, CONSTRAINT `
child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent`
(`id`) ON DELETE RESTRICT)