코드로 보는 정리
create database product;//product라는 database를 하나 만듦
show databases; //모든 데이터베이스를 보여줌
use product; //product라는 데이터베이스를 사용
show tables; //product에 들어있는 모든 table을 보여줌
create table product (
product_name varchar(20) not null,
cost int,
make_date varchar(20) not null,
company varchar(20) not null,
amount int
);
insert into product values("바나나", 1500, "2021-07-01", "델몬트", 17);
//product table에 바나나에 대한 정보를 삽입
select * from product.product; //product 데이터베이스의 product table에 모든 요소를 보여줌
// * 연산자를 사용하면 모든 열을 선택한다는 의미
select product_name, cost from product.product; //product table에서 이름과 가격만을 출력
select * from product.product where product_name = "바나나"; //product table에서 상품 이름이 "바나나"인 요소만 출력
delete from product where product_name = "바나나";//product table에서 상품 이름이 바나나인 행을 삭제
drop table product;//product table을 삭제
truncate product;//product table의 모든 행을 삭제
기본 용어
기본 키 제약조건
create table person
(person_id smallint unsigned,
fname varchar(20),
lname varchar(20),
eye_color ENUM('BR', 'BL', 'GR'),
birth_date date,
street varchar(20),
city varchar(20),
state varchar(20),
country varchar(20),
postal_code varchar(20),
constraint pk_person primary key (person_id)
);
테이블을 정의할 때는 기본 키로 사용할 열을 데이터베이스 서버에 알려줘야 하므로 테이블에 제약조건(constraint)을 만들어 이 작업을 수행한다. 위의 코드에서는 기본키 제약조건을 사용했는데 person_id 열에 생성되며 pk_person이라는 이름이 지정된다. eye_color에 적용된 enum이 의미하는 것은 eye_color 열에 'BR' 또는 'BL'과 같이 특정 열에 대해 허용 가능한 값을 표시한 것이다. 이것을 체크 제약조건이라고 한다.
생성한 테이블에 대한 정보를 얻고 싶으면 다음 문장을 실행하면 된다.
desc person;
create table favorite_food
(person_id smallint unsigned,
food varchar(20),
constraint pk_favorite_food primary key (person_id, food),
constraint fk_fav_food_person_id foreign key (person_id)
references person (person_id)
);
한 사람이 좋아하는 음식이 두 가지 이상일 수 있으므로 테이블의 고유성을 보장하려면 person_id 열 이상의 것이 필요하다. 따라서 이 테이블에는 person_id와 food라는 두 개의 기본 키가 있다.
favorite_food 테이블에는 외래 키 제약조건이라는 또 다른 유형의 제약조건이 포함된다. 이렇게 하면 favorite_food 테이블에서 person_id 열의 값에 person 테이블에 있는 값만 포함되도록 제한된다. 예를 들어, 이 제약조건이 있는 상황에서 person 테이블에 person_id가 27인 행이 아직 없다면, favorite_food 테이블에도 person_id가 27인 사람이 피자를 좋아한다는 것을 추가할 수 없다.
데이터 삽입
테이블의 모든 열이 not null로 정의되어 있지 않는 한, 테이블의 모든 열에 데이터를 제공할 필요는 없다. 경우에 따라 초기 insert 문에 포함되지 않은 열에는 나중에 update 문을 통해 값을 지정할 수 있다.
숫자 키 데이터 생성
alter table person modify person_id smallint unsigned auto_increment;
//이 구문은 기본적으로 person 테이블의 person_id 열을 재정의한다.
//이제 person 테이블에 데이터를 삽입할 때 person_id 열에 null 값을 제공하기만 하면 MySQL은 사용 가능한 다음 숫자로 열을 채운다.(기본적으로 1부터 시작)
insert 문
insert into person
(person_id, fname, lname, eye_color, birth_date)
values (null, 'William', 'Turner', 'BR', '1972-05-27');
insert into favorite_food (person_id, food) values(1, 'pizza');
insert into favorite_food (person_id, food) values(1, 'cookies');
insert into favorite_food (person_id, food) values(1, 'nachos');
select food from favorite_food where person_id = 1 order by food;

insert into person (person_id, fname, lname, eye_color, birth_date, street, city, state, country, postal_code) values (null, 'Susan', 'Smith', 'BL', '1975-11-02', '23 Maple St.', 'Arlington', 'VA', 'USA', '20220');
select person_id, fname, lname, birth_date from person;

데이터 수정
update person set street = '1225 Tremont St.', city = 'Boston', state = 'MA', country = 'USA', postal_code = '02138' where person_id = 1;
데이터 삭제
delete from person where person_id = 2;
기본 날짜 형식 사용하지 않기(str_to_date 함수)
update person set birth_date = str_to_date('DEC-21-1980', '%b-%d-%Y') where person_id = 1;
쿼리 절
열의 별칭 지정하기
select language_id, 'COMMON' as language_usage, language_id * 3.1415927 as lang_pi_value, upper(name) as language_name from language;

중복 제거
select distinct actor_id from film_actor order by actor_id;
테이블 유형
파생 테이블
select concat(cust.last_name, ', ', cust.first_name) as full_name from (select first_name, last_name, email from customer where first_name = 'JESSIE') as cust;

임시 테이블
mysql> create temporary table actors_i(
-> actor_id smallint(5),
-> first_name varchar(45),
-> last_name varchar(45)
-> );
mysql> insert into actors_i select actor_id, first_name, last_name from actor where last_name like "J%";
mysql> select * from actors_i;

가상 테이블(뷰)
mysql> create view cust_vw as select customer_id, first_name, last_name, active from customer;
mysql> select first_name, last_name from cust_vw where active = 0;

테이블 연결
mysql> select customer.first_name, customer.last_name, time(rental.rental_date) rental_time from customer inner join rental on customer.customer_id = rental.customer_id where date(rental.rental_date) = '2005-06-14';
테이블 별칭 정의
mysql> select c.first_name, c.last_name, time(r.rental_date) as rental_time from customer as c inner join rental as r on c.customer_id = r.customer_id where date(r.rental_date) = '2005-06-14';
where 절
mysql> select title from film where rating = 'g' and rental_duration >= 7;
mysql> select title from film where (rating = 'G' and rental_duration >= 7) or (rating = 'PG-13' and rental_duration <= 3);
group by 절과 having 절
mysql> select c.first_name, c.last_name, count(*) from customer as c inner join rental as r on c.customer_id = r.customer_id group by c.first_name, c.last_name having count(*) >= 40;
order by 절
일반적으로 쿼리에서 반환된 결과셋의 행은 특정 순서대로 나열되지 않는다. 결과셋을 원하는 기준으로 정렬하려면 서버에서 order by 절을 사용하여 정렬하도록 지시해야 한다. order by 절은 원시 열 데이터 또는 열 데이터를 기반으로 표현식을 사용하여 결과셋을 정렬하는 메커니즘이다.
결과셋을 성을 기준으로 알파벳순 정렬되도록 하려면 order by 절에 last_name 열을 추가한다.
mysql> select c.first_name, c.last_name, time(r.rental_date) rental_time from customer as c inner join rental as r on c.customer_id = r.customer_id where date(r.rental_date) = '2005-06-14' order by c.last_name;
이 예제에는 그런 사례가 없지만, 대규모 고객 목록에는 종종 같은 성을 가진 사람이 여럿 포함되므로 정렬 기준을 확장하여 사람의 이름도 포함할 수 있다. order by 절에서 last_name 열 뒤에 first_name 열을 추가하면 된다.
정렬은 기본적으로 오름차순으로 이루어지지만 내림차순 정렬을 사용하려면 order by 절 마지막에 desc 키워드를 추가해야 한다.
순서를 통한 정렬
mysql> select c.first_name, c.last_name, time(r.rental_date) rental_time from customer as c inner join rental as r on c.customer_id = r.customer_id where date(r.rental_date) = '2005-06-14' order by 3 desc;