테이블의 각 레코드 식별
중복되지 않은 고유값 포함
null값을 포함할 수 없음
테이블 당 하나의 기본키를 가짐
-- 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;
-- 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;
한 테이블을 다른 테이블과 연결해 주는 역할
참조되는 테이블의 항목은 그 테이블의 기본키(혹은 단일값)
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 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;
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
alter table tablename
drop foreign key FK_constraint;
alter table tablename
add foreign key (column) reference ref_tablename(ref_column)
여러 칼럼 혹은 테이블 전체 칼럼으로부터 하나의 결과값을 변환하는 함수
총 개수를 계산해주는 함수
select count(column)
from tablename
where conditon;
숫자 칼럼의 합계를 계산해 주는 함수
select sum(coulmn)
from tablename
where condition;
select count(distinct name) #same as unique
from police_station;
select distinct name from police_station;
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 '검거';