[SQL] 연습

[SQL] SQL 기본(3편)

Simon Yoon 2022. 2. 1. 14:53

모든 쿼리는 mysql에서 작성

 

서브 쿼리

1. 서브 쿼리 기본

# 전체 나라수, 전체 도시수, 전체 언어수를 1개의 row로 출력
use world;
select
(select count(*) from country) as total_country,
(select count(*) from city) as total_city,
(select count(distinct language) from countrylanguage) as total_language
from dual
;

DUAL 테이블을 이용하여 SELECT절에서 다양한 연산 처리를 할 수 있다.

 

# 국토 면적이 가장 넓은 나라를 출력
# 서브 쿼리를 이용해서 한 개의 sql문으로 출력할 수 있다
select code, name, surfacearea
from country
where surfacearea = (
	select max(surfacearea)
	from country
);

 

2. JOIN 사용

# 인구수가 800만 이상이 되는 도시의 국가코드, 국가이름, 도시인구수 출력
select country.code, country.name, city.name, city.population
from (
	select countrycode, name, population
	from city
	where population >= 800 * 10000
) as city
join country
on country.code = city.countrycode
;

 

3. WHERE 활용

# 900만 이상의 인구를 가진 도시 국가의 국가코드, 국가이름, 대통령이름 출력
select code, name, headofstate
from country
where code in (
	select countrycode
	from city
	where population >= 900 * 10000
    )
;

 

뷰(View)

뷰는 가상의 테이블로 실제로 존재하지는 않지만 있는 것으로 간주된다. 임시적인 작업을 위해 사용하고 수정 및 인덱스 설정은 할 수 없다.

 

1. 인라인 뷰(inline view)

# select문의 from절 내부에 있는 또 다른 select문을 inline view라고 한다.
select A.*
from (
	select code, name, population
	from country
) A
;

인라인 뷰 안에 인라인 뷰도 가능하다

 

2. 뷰를 만들면 select문을 반복적으로 작성할 필요 없이 해당 뷰를 select하면 되므로, 쿼리를 간단하게 작성할 수 있다.

# 도시인구가 900만이 넘는 나라를 출력하기 위한 쿼리
select country.code, country.name, city.name, city.population
from (select countrycode, name, population 
	  from city
      where population >= 9000000) as city
join country
on country.code = city.countrycode;

# view 생성
create view city_900 as
select countrycode, name, population 
from city
where population >= 9000000;

# 동일한 결과를 view를 생성해놓으면 간단하게 불러올 수 있다.
select country.code, country.name, city.name, city.population
from city_900 as city
join country
on country.code = city.countrycode;

 

'[SQL] 연습' 카테고리의 다른 글

[DB] mysql에서 한글 포함된 쿼리 insert 안될 때  (0) 2022.06.11
[DB] MongoDB  (0) 2022.05.01
[SQL] SQL 기본(2편)  (0) 2022.01.30
[SQL] SQL 기본(1편)  (0) 2022.01.29
[SQL] 데이터 베이스 기본  (0) 2022.01.27