Part 05. SQL_Chapter 14. PRIMARY KEY, FOREIGN KEY

수야·2023년 7월 28일
0

primary key(기본키)

테이블의 각 레코드 식별
중복되지 않은 고유값 포함
null값을 포함할 수 없음
테이블 당 하나의 기본키를 가짐

primary key 생성 문법

-- create table tablename(
-- 	column1 datatype not NULL,
--     column2 datatype not NULL,
--     constraint constraint_name <-생략 가능
-- 		primary key (column1, colum2...)
-- )

하나의 칼럼을 기본 키로 사용하는 경우

create table person(
	pid int not null,
    name varchar(16),
    age int,
    sex char,
    primary key(pid)
);

desc person;

여러개의 칼럼을 기본 키로 사용하는 경우

create table animal(
	name varchar(16) not null,
    type varchar(16) not null,
    age int,
    primary key (name, type)
);
desc animal;

primary key 삭제 문법

-- alter table tablename
-- drop primary key;#키는 하나밖에 없기 때문에 굳이 이름을 안줘도 됨

하나의 칼럼이 기본키로 설정된 경우

alter table person
drop primary key;

desc person;

여러개의 칼럼이 기본키로 설정된 경우(삭제하는 방법 동일)

alter table animal
drop primary key;

desc animal;

이미 있는 테이블에 키를 부여하는 경우

-- alter table tablename
-- add primary key (column1, column2,...)

하나의 칼럼을 기본 키로 지정하는 경우

alter table person
add primary key(pid);

desc person;

여러개의 칼럼을 기본 키로 지정하는 경우

alter table animal
add constraint PK_animal primary key(name, type);
# constraint PK_animal 생략 가능

desc animal;

foregin key(외래키)

한 테이블을 다른 테이블과 연결해 주는 역할
참조되는 테이블의 항목은 그 테이블의 기본키(혹은 단일값)

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 kry (column3, column4,...) references ref_tablename(ref_column)
);

create table에서 foreign key를 지정하는 경우

create table orders(
	 oid int not null,
     order_no varchar(16),
     pid int,
     primary key (oid),
     constraint fk_person foreign key (pid) references person (pid)
);

desc orders;

자동 생성된 contsraint를 확인하는 방법

show create table tablename;

예제

show create table person;
CREATE TABLE `person` (
   `pid` int NOT NULL,
   `name` varchar(16) DEFAULT NULL,
   `age` int DEFAULT NULL,
   `sex` char(1) DEFAULT NULL,
   PRIMARY KEY (`pid`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

foreign key 삭제 방법

alter table tablename
drop foreign key FK_constraint;

테이블이 생성된 이후에 foregin key를 지정하는 방법

alter table tablename
add foreign key (column) reference ref_tablename(ref_column) 
  • 단, 참조가 되는 레퍼런스 테이블의 칼럼은 기본 키로 설정되어있어야함

집계함수

여러 칼럼 혹은 테이블 전체 칼럼으로부터 하나의 결과값을 변환하는 함수

count

총 개수를 계산해주는 함수

select count(column)
from tablename
where conditon;

sum

숫자 칼럼의 합계를 계산해 주는 함수

select sum(coulmn)
from tablename
where condition;

예제

  • police_station에서 경찰서는 총 몇개이고, 각각 경찰서 이름은 무엇인지 확인하세요.
select count(distinct name) #same as unique
from police_station;
select distinct name from police_station;
  • crime_status 에서 status_type은 총 몇개이고, 각각 타입은 무엇인지 확인하세요.
select count(distinct 죄종) from crime_status;

select distinct 죄종 from crime_status;

종로경찰서와 남대문경찰서의 강도발생 건수의 합을 구하세요

select sum(건수)
from crime_status
where 죄종 = '강도' and (구분 ='종로' or 구분 ='남대문');

폭력범죄의 검거 건수 합을 구하세요

select sum(건수)
from crime_status
where 죄종 like '폭력' and 발생검거 like '검거';
profile
수야는 코린이에서 더 나아갈거야

0개의 댓글