SQL

기본키(pk), 외래키(fk) 동시 적용

열심히 해 2024. 10. 4. 10:57

아래처럼 해도 되는데 오류가 났습니다.

 

원인: 타입이 달랐기 때문입니다.

CREATE TABLE IF NOT EXISTS user
(
    userName varchar(100) not null comment '작성자명',
    IdentificationNumber decimal(13) primary key comment '주민(외국인)등록번호',
    eMail varchar(255) not null comment '이메일',
    creationDate datetime not null DEFAULT CURRENT_TIMESTAMP comment '작성일',
    modifiedDate datetime not null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '수정일',
    foreign key(IdentificationNumber) references plan(id)
);

 

기본키이면서 동시에 외래키로 설정하기 위해 위와 같이 입력하면 오류가 났습니다.

Referencing column 'IdentificationNumber' and referenced column 'id' in foreign key constraint 'user_ibfk_1' are incompatible.

 

CREATE TABLE IF NOT EXISTS user (
userName varchar(100) not null comment '작성자명',
IdentificationNumber decimal(13) not null comment '주민(외국인)등록번호', -- 칼럼 등록
eMail varchar(255) not null comment '이메일',
creationDate datetime not null DEFAULT CURRENT_TIMESTAMP comment '작성일',
modifiedDate datetime not null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '수정일',
PRIMARY KEY (IdentificationNumber), -- 기본키 설정
CONSTRAINT fk_plan_identification FOREIGN KEY (IdentificationNumber) REFERENCES plan(id) -- 외래키 설정
);

 

우선 칼럼을 등록하고
기본키로 설정 후

제약조건(외래키 설정)을 추가하는 방식을 썼습니다. 

에러 : 

Referencing column 'IdentificationNumber' and referenced column 'id' in foreign key constraint 'fk_plan_identification' are incompatible.

 

 

.... 원인은 plan 의 id (bigint)와 user의 IdentificationNumber(decimal) 의 타입이 달랐기 때문입니다.

CREATE TABLE IF NOT EXISTS user
(
    userName varchar(100) not null comment '작성자명',
    IdentificationNumber bigint primary key comment '주민(외국인)등록번호',
    eMail varchar(255) not null comment '이메일',
    creationDate datetime not null DEFAULT CURRENT_TIMESTAMP comment '작성일',
    modifiedDate datetime not null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP comment '수정일',
    foreign key(IdentificationNumber) references plan(id)
);

 

'SQL' 카테고리의 다른 글

DB, RDB, DBMS, RDBMS  (1) 2024.12.09
WITH절 - CTE 구문 만들기.  (0) 2024.11.11
SQL - DDL, DML  (0) 2024.10.02
SQL 기초2  (0) 2024.08.25
SQL 기초  (0) 2024.08.23