Engineering Note

[Database] MySQL 외래키 예외 본문

Computer Science/Database

[Database] MySQL 외래키 예외

Software Engineer Kim 2025. 10. 5. 23:12

 

MySQL로 데이터베이스를 연습하면서, 게시판 프로젝트로 데이터베이스를 설계하고 SQL로 직접 테이블을 조작해보면서 에러가 발생했다.

실행 쿼리

INSERT INTO likes (member_id, content, comemnt_id) values(1, "내용", 100)    Error Code: 1054. Unknown column 'content' in 'field list'

 

 

 

 

에러메세지

cannot add or update a child row: a foreign key constraint

 

 

 

에러 원인 분석

 

첫 번째 원인

좋아요 like 테이블에 데이터를 넣으려고 했는데 like 테이블의 부모 comment_id 부모 PK값이 없어서 발생한 오류다.

 

두 번째 원인

  1. content 컬럼 - likes 테이블에 없는 컬럼
  2. comemnt_id - 오타 (comment_id가 맞음)

 

해결 방법

-- 1. 댓글이 없으면 먼저 생성
INSERT INTO comment (content, board_id, member_id) 
VALUES ('좋은 글이네요!', 1, 1);


-- 2. 생성된 comment_id 확인
SELECT comment_id FROM comment ORDER BY comment_id DESC LIMIT 1;
-- 예: comment_id = 1

-- 3. 이제 좋아요 추가
INSERT INTO likes (member_id, comment_id) 
VALUES (1, 1);  -- 존재하는 comment_id 사용

 

 

Comments