๐ SQL Subquery
- ํ๋์ SQL ๋ฌธ ์์ ํฌํจ๋์ด ์๋ ๋ ๋ค๋ฅธ SQL ๋ฌธ์ ๋งํ๋ค
- ๋ฉ์ธ ์ฟผ๋ฆฌ๊ฐ ์๋ธ ์ฟผ๋ฆฌ๋ฅผ ํฌํจํ๋ ์ข ์์ ์ธ ๊ด๊ณ
- Subquery๋ ๊ดํธ๋ก ๋ฌถ์ด์ ์ฌ์ฉํ๋ค
- ๋จ์ผ ํ or ๋ณต์ ํ ๋น๊ต ์ฐ์ฐ์์ ํจ๊ป ์ฌ์ฉ ๊ฐ๋ฅ
- Subquery ์์๋ order by๋ฅผ ์ฌ์ฉํ ์ ์๋ค.
๐ Subquery ์ข ๋ฅ
- Scalar subquery, Inline View, Nested subquery
๐งท Scalar subquery
- SELECT ์ ์ ์ฌ์ฉ, ์๋ธ ์ฟผ๋ฆฌ์์๋ ํ๋์ column ๋ง ๋ฐ๋๋ค
SELECT column1, (select column2 from table2 where condition)
from table1
where condition;
select case_number,
(select avg(case_number) from crime_status
where crime_type = '๊ฐ๋' and status_type = '๊ฒ๊ฑฐ') avg
from crime_status
where police_station ='์ํ' and crime_type = '๊ฐ๋' and status_type = '๊ฒ๊ฑฐ';
๐งท Inline View
- From ์ ์ ์ฌ์ฉ, main query ์์๋ ์ธ๋ผ์ธ ๋ทฐ ์์ ์กฐํํ column๋ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค
select a.column, b.column
from table1 a, (select column1, column2 from table2) b
where condition;
select c.police_station, c.crime_type, c.case_number from crime_status c,
(select police_station, max(case_number) count from crime_status
where status_type = '๋ฐ์'
group by police_station) m
where c.police_station = m.police_station
AND c.case_number = m.count;
๐งท Nested query
- Where ์ ์์ ์ฌ์ฉํ๋ ์๋ธ์ฟผ๋ฆฌ (single row, multiple row, multiple column ๋ฑ์ด ์๋ค)
๐ Single row
- ๋น๊ต ์ฐ์ฐ์์ ํจ๊ป ์ฌ์ฉ
- single row subquery๋ ๋ฐ๋์ 1๊ฐ์ ํ๋ง ๋ฆฌํด์ด ๋์ด์ผ ํ๋ค. (๋น๊ต ์ฐ์ฐ์์ ํจ๊ป ์ฌ์ฉ๋๊ธฐ ๋๋ฌธ)
select name from celeb where name = (select host from snl_show where id = 1);
# single row subquery๋ ๋ฌด์กฐ๊ฑด 1๊ฐ์ row๋ง ๋ฆฌํด์ด ๋์ด์ผ ํ๋ค (๋น๊ต๋ฅผ ํด์ผํ๊ธฐ ๋๋ฌธ์)
๐ multiple row
- ๋ณต์์ ํ์ด ๋ฆฌํด์ด ๋๋ค
- in, exists, any, all ๋ฑ ์ฌ์ฉ๋๋ค
- IN
select host from snl_show
where host
in (select name from celeb where job_title like '%์ํ๋ฐฐ์ฐ%');
- EXISTS
select p.name from police_station p
where exists (select police_station from crime_status c
where p.name = c.reference and case_number > 2000);
- ANY
- ์๋ธ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ์ค ์ต์ํ ํ๋๋ผ๋ ๋ง์กฑํ๋ฉด return
select name from celeb
where name = any(select host from snl_show);
- ALL
- ์๋ธ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ชจ๋ ๋ง์กฑํ๋ฉด return
select column_names from table_name
where column_name = ALL (select column_name from table_name where condition)
order by column_names;
๐ Multicolumn subquery
select name, sex, agency from celeb
where (sex, agency) in (select sex, agency from celeb where name = '๊ฐ๋์');
'Study_note(zb_data) > SQL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SQL ์๋ ๊ฒฝ๋๋ฅผ ํ์ฉํ์ฌ ๊ฑฐ๋ฆฌ ๊ณ์ฐํ๊ธฐ (0) | 2023.09.17 |
---|---|
SQL ๋ ์ง ํ์ DATE_FORMAT ํ์ฉํ๊ธฐ (0) | 2023.09.14 |
์คํฐ๋ ๋ ธํธ (Scalar Functions) (0) | 2023.08.30 |
์คํฐ๋ ๋ ธํธ (SQL ์ง๊ณํจ์, group by, having) (0) | 2023.08.30 |
์คํฐ๋ ๋ ธํธ (SQL, Primary Key, Foreign Key) (0) | 2023.08.30 |