๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Study_note(zb_data)/SQL

์Šคํ„ฐ๋”” ๋…ธํŠธ (SQL Subquery)

๐Ÿ“Œ 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 = '๊ฐ•๋™์›');