๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

RDB๐Ÿ—‚๏ธ

SQL ์ œ์•ฝ์กฐ๊ฑด

728x90

AUTO_INCREMENT : ์ปฌ๋Ÿผ์˜ ๊ณ ์œ ๋ฒˆํ˜ธ๋ฅผ 1์”ฉ ์ฆ๊ฐ€์‹œ์ผœ ๋ถ€์—ฌํ•˜์—ฌ ์ƒ์„ฑํ•ด์ค๋‹ˆ๋‹ค.

(์ด์šฉํ•˜๋ ค๋ฉด ํ•ด๋‹น ์ปฌ๋Ÿผ์— value๋ฅผ ์ฃผ์ง€ ์•Š์œผ๋ฉด ๋œ๋‹ค)

CREATE TABLE ํ…Œ์ด๋ธ”์ด๋ฆ„
(
    ํ•„๋“œ์ด๋ฆ„ ํ•„๋“œํƒ€์ž… AUTO_INCREMENT,
    // id bigint AUTO_INCREMENT,
    ...
);

NOT NULL : NULL ๊ฐ’์„ ์ €์žฅํ•  ์ˆ˜ ์—†๋‹ค.

UNIQUE : ํ•ด๋‹น ํ•„๋“œ๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๊ฐ’์„ ๊ฐ€์ ธ์•ผํ•œ๋‹ค.

 

PRIMARY KEY(๊ธฐ๋ณธ ํ‚ค) : ๋ฐ์ดํ„ฐ์˜ ์ค‘๋ณต์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด / ๊ธฐ๋ณธ ํ‚ค ~ ์ธ๋ฑ์Šค๋ฅผ ๋งŒ๋“ค์–ด ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜ ์†๋„๋ฅผ ํ–ฅ์ƒํ•˜๊ธฐ ์œ„ํ•ด

๊ธฐ๋ณธ ํ‚ค ํ•„๋“œ๊ฐ€ NOT NULL๊ณผ UNIQUE ์ œ์•ฝ์กฐ๊ฑด์˜ ํŠน์ง•์„ ๋ชจ๋‘ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค.

ex)

create table member
( 	mem_id char(8) not null primary key,
		mem_name varchar(10) not null,
    height tinyint unsigned null
);

 

FOREIGN KEY : ํ•˜๋‚˜์˜ ํ…Œ์ด๋ธ”์„ ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”์— ์˜์กดํ•˜๊ฒŒ ๋งŒ๋“ค๋ฉฐ ๋ฐ์ดํ„ฐ์˜ ๋ฌด๊ฒฐ์„ฑ์„ ๋ณด์žฅ

CREATE TABLE ํ…Œ์ด๋ธ”์ด๋ฆ„
(
    ํ•„๋“œ์ด๋ฆ„ ํ•„๋“œํƒ€์ž…,
    ...
		FOREIGN KEY(ํ•„๋“œ์ด๋ฆ„)
    REFERENCES ํ…Œ์ด๋ธ”์ด๋ฆ„(ํ•„๋“œ์ด๋ฆ„)
);

FK์˜ ๊ธฐ์ค€ ํ…Œ์ด๋ธ”์˜ ์—ด์€ ๋ฐ˜๋“œ์‹œ PK,UNIQUE ์ œ์•ฝ์กฐ๊ฑด์ด ์„ค์ •๋˜์–ด ์žˆ์–ด์•ผํ•œ๋‹ค.

ex)

create table buy
( 	num int auto_increment not null primary key,
		mem_id char(8) not null,
    prod_name char(6) not null,
    foreign key(mem_id) references member(mem_id)
);

 

CASCADE : FOREIGN KEY๋กœ ์—ฐ๊ด€๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œ, ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋‹ค.

CREATE TABLE ํ…Œ์ด๋ธ”์ด๋ฆ„
(
    ํ•„๋“œ์ด๋ฆ„ ํ•„๋“œํƒ€์ž…,
    ...
		FOREIGN KEY(ํ•„๋“œ์ด๋ฆ„)
    REFERENCES ํ…Œ์ด๋ธ”์ด๋ฆ„(ํ•„๋“œ์ด๋ฆ„) ON DELETE CASCADE 
														 //ON UPDATE CASCADE
);

ex)

create table buy
( 	num int auto_increment not null primary key,
		mem_id char(8) not null,
    prod_name char(6) not null,
    foreign key(mem_id) references member(mem_id) 
    on update cascade 
    on delete cascade
);

์˜ˆ์‹œ์˜ ๊ฒฝ์šฐ member ํ…Œ์ด๋ธ”์„ ์ฐธ์กฐํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— member ํ…Œ์ด๋ธ”์„ ์ˆ˜์ •ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•˜๋Š” ๊ฒฝ์šฐ ๊ทธ ๋‚ด์šฉ์ด buy ํ…Œ์ด๋ธ”์—๋„ ํ•จ๊ป˜ ๋ฐ˜์˜๋˜์–ด ๋ฐ์ดํ„ฐ์˜ ๋ฌด๊ฒฐ์„ฑ์ด ์œ ์ง€๋œ๋‹ค.

 

๊ธฐํƒ€ ์ œ์•ฝ์กฐ๊ฑด

์ฒดํฌ ์ œ์•ฝ์กฐ๊ฑด : ์กฐ๊ฑด์— ๋งŒ์กฑํ•˜๋Š” ๊ฐ’๋งŒ ์ž…๋ ฅ ๊ฐ€๋Šฅ (CHECK)

 

๊ธฐ๋ณธ ๊ฐ’ ์ •์˜ : ๊ฐ’์„ ์ž…๋ ฅํ•˜์ง€ ์•Š์•˜์„ ๋•Œ ์ž๋™์œผ๋กœ ์ž…๋ ฅ๋  ๊ฐ’์„ ๋ฏธ๋ฆฌ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋‹ค (DEFAULT)

 

Null ํ—ˆ์šฉ : NULL or NOT NULL

728x90