Primary key
테이블의 각 레코드 식별
중복되지 않은 고유값 포함
NULL 값 포함 불가
테이블 당 하나의 기본키를 가짐
프라이머리 키 삽입
mysql> create table person
-> (
-> pid int NOT NULL,
-> name varchar(16),
-> age int,
-> sex char,
-> primary key (pid)
-> );
프라이머리 키 삭제
mysql> alter table person
-> drop primary key;
기 완성 테이블 프라이머리 키 지정
mysql> alter table person
-> add primary key(pid);
기 완성 테이블 프라이머리 키 지정2
mysql> alter table animal
-> add constraint PK_animal
-> primary key (name,type);
*add constraint = 제약조건 추가
Foreign Key
한 테이블을 다른 테이블과 연결해주는 역할,
참조되는 테이블의 항목은 그 테이블의 기본키(혹은 단일값)
만들기
mysql> 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)
-> );
FK_person 이라는 이름으로 person 테이블의 pid를 가져온다
삭제
mysql> alter table orders
-> drop foreign key FK_person;
예제풀이
데이터베이스-1 접속
crime_status / police_station 이용
컬럼 중복제거 후 개수 확인
mysql> select count(distinct name) from police_station;
mysql> select count(distinct police_station) from crime_status;
매칭
mysql> select c.police_station, p.name
-> from crime_status c, police_station p
-> where p.name like concat('서울', c.police_station, '경찰서')
-> group by c.police_station, p.name;
name을 프라이머리 키로 설정