데이터로그😎
서브 쿼리 본문
아래 문제에서 사용하는 데이터: world database
https://dev.mysql.com/doc/index-other.html
MySQL :: Other MySQL Documentation
Other MySQL Documentation This page provides additional documentation. There's even more available on these extra pages: MySQL Server Doxygen Documentation Title HTML Online MySQL Server (latest version) View Expert Guides Language Title Version HTML Onlin
dev.mysql.com
전체 나라 수, 전체 도시 수, 전체 언어의 수를 출력
use world;
SELECT
(SELECT count(*) FROM country) as country_cnt,
(SELECT count(*) FROM city) as city_cnt,
(SELECT count(Language) FROM countrylanguage) as language_cnt
from dual;
인구가 800만 이상이 되는 도시의 국가코드, 이름, 도시 인구수 출력
✅ step1: 인구 800만 이상인 도시 필터링 (table: city)
✅ step2: step1 테이블을 서브쿼리로
✅ step3: 국가 코드, 이름 테이블과 step2 테이블 조인 (table: country)
# step 1) city 테이블 필터링 하기
select name as 'city_name', countrycode, population
from city
where population >= 8000000;
# step 2) 서브 쿼리로 사용하기(FROM절)
# sub-query만들었으면 반드시 테이블 알리아스 붙여라.
select *
from ( select name as 'city_name', countrycode, population
from city
where population >= 8000000 ) as city_pop_over_800 ;
# step 3) 다른 테이블과의 조인. 같은 테이블과의 조인을 수행하는 것 = self- join
SELECT city_pop_over_800.city_name,
country_simple.name,
city_pop_over_800.population
FROM ( select name as 'city_name', countrycode, population
from city
where population >= 8000000 ) as city_pop_over_800
JOIN ( select code, name from country ) as country_simple
ON city_pop_over_800.countrycode = country_simple.code;
반응형
'SQL > MySQL' 카테고리의 다른 글
Null과 공백의 차이 & Null값의 처리 (0) | 2023.09.08 |
---|---|
[윈도우 함수] SUM() OVER() (0) | 2023.09.06 |
ERD 표기법 (0) | 2023.09.06 |
python - mysql 연결 (0) | 2023.09.06 |
JOIN (1) | 2023.09.05 |