[TIL] SQL/Key

HYERINยท2024๋…„ 2์›” 10์ผ

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
7/13
post-thumbnail

๐Ÿ“– ์ด๋ก 

๐Ÿ“Œ ย  Primary Key (๊ธฐ๋ณธํ‚ค)

  • ํ…Œ์ด๋ธ”์˜ ๊ฐ ๋ ˆ์ฝ”๋“œ๋ฅผ ์‹๋ณ„
  • ์ค‘๋ณต๋˜์ง€ ์•Š์€ ๊ณ ์œ ๊ฐ’์„ ํฌํ•จ
  • NULL ๊ฐ’์„ ํฌํ•จํ•  ์ˆ˜ ์—†์Œ
  • ํ…Œ์ด๋ธ” ๋‹น ํ•˜๋‚˜์˜ ๊ธฐ๋ณธํ‚ค๋ฅผ ๊ฐ€์ง

๐Ÿ“Œ ย  Foreign Key (์™ธ๋ž˜ํ‚ค)

  • ํ•œ ํ…Œ์ด๋ธ”์„ ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”๊ณผ ์—ฐ๊ฒฐํ•ด์ฃผ๋Š” ์—ญํ• 
  • ์ฐธ์กฐ๋˜๋Š” ํ…Œ์ด๋ธ”์˜ ํ•ญ๋ชฉ์€ ๊ทธ ํ…Œ์ด๋ธ”์˜ ๊ธฐ๋ณธํ‚ค (ํ˜น์€ ๋‹จ์ผ๊ฐ’)

๐Ÿ’ป ์‹ค์Šต

Primary Key ๋ฌธ๋ฒ•

//create table ์—์„œ Primary key๋ฅผ ์„ค์ •
create table tablename
(
	column1 datatype not null,
    column2 datatype not null,
    ...
    constraint constraint_name
    primary key (column1, column2, ...)
)

// ํ…Œ์ด๋ธ” ์ƒ์„ฑ ํ›„ Primary Key ์ถ”๊ฐ€
alter table tablename
add primary key (column1, column2, ...) 

Primary Key ์‚ญ์ œ ๋ฌธ๋ฒ•

alter table tablename
drop primary key(column) 

Foreign Key ๋ฌธ๋ฒ•

//create table ์—์„œ foreign key๋ฅผ ์„ค์ •
create table tablename
(
	column1 datatype not null,
    column2 datatype not null,
    column3 datatype,
    column4 datatype,
    ...
    constraint constraint_name //์ƒ๋žต๊ฐ€๋Šฅ
      primary key (column1, column2, ...),
    constraint constraint_name //์ƒ๋žต๊ฐ€๋Šฅ
      foreign key (column3, column4, ...) references ref_tablename(ref_column)
)

// table ์ƒ์„ฑ ํ›„ foreign key ์ถ”๊ฐ€
alter table tablename
add foreign key(column) references ref_tablename(ref_column)

์ž๋™ ์ƒ์„ฑ๋œ CONSTRAINT ๋ฅผ ํ™•์ธ

show create table tablename

Foreign Key ์‚ญ์ œ ๋ฌธ๋ฒ•

alter table tablename
drop foreign key constraint_name

๐Ÿงธ review

  • orders table
create table orders
(
  order_id int not null primary key,
  user_id int,
  product varchar(32)
);
  • users table
create table users
(
  id int not null primary key,
  pw varchar(16) not null,
  name varchar(16) not null,
  email varchar(32)
);
  • orders ํ…Œ์ด๋ธ”์˜ primary key ์‚ญ์ œ
alter table orders
drop primary key;

orders ํ…Œ์ด๋ธ”์˜ foreign key ์‚ญ์ œ

alter table orders
drop foreign key orders_ibfk_1; // ์ž๋™์œผ๋กœ ์ƒ์„ฑ๋œ constraint_name
  • orders ํ…Œ์ด๋ธ”์˜ user_id ๋ฅผ users ํ…Œ์ด๋ธ”์˜ id ์™€ ์—ฐ๊ฒฐ๋œ foreign key ๋“ฑ๋ก
alter table orders
add foreign key (user_id) references users (id);
  • orders ํ…Œ์ด๋ธ”์˜ order_id ๋ฅผ primary key ๋กœ ๋“ฑ๋ก
alter table orders
add primary key(order_id);

์‹ค์Šตํ™•์ธ

ordersusers
constraint_name ํ™•์ธ

0๊ฐœ์˜ ๋Œ“๊ธ€