<8์ฃผ_1์ผ> ๐Ÿ’กSQL subsquery

Nary Kimยท2023๋…„ 6์›” 27์ผ
0

๐Ÿ’กSQL subsquery

scalar subquary

select์ ˆ์—์„œ ์‚ฌ์šฉ.
๊ฒฐ๊ณผ๋Š” ํ•˜๋‚˜์˜ column์ด์–ด์•ผํ•จ.

์˜ˆ์ œ

oil_priceํ…Œ์ด๋ธ”์—์„œ ์…€ํ”„์ฃผ์œ ์†Œ์˜ ํ‰๊ท ๊ฐ€๊ฒฉ๊ณผ SK์—๋„ˆ์ง€์˜ ๊ฐ€์žฅ ๋น„์‹ผ ๊ฐ€๊ฒฉ์„ ์กฐํšŒํ•˜์‹œ์˜ค.

mysql> select max(๊ฐ€๊ฒฉ) SK์ฃผ์œ ์†Œ์ตœ๋Œ€๊ฐ’, 
    ->(select avg(๊ฐ€๊ฒฉ) from oil_price where ์…€ํ”„='Y') ์…€ํ”„์ฃผ์œ ์†Œํ‰๊ท ๊ฐ’ 
    ->from oil_price where ์ƒํ‘œ like '%SK%';

inline view

from ์ ˆ์— ์‚ฌ์šฉํ•˜๋Š” subquary
mainquary ์—์„œ๋Š” inline view์—์„œ ์กฐํšŒํ•œ column๋งŒ ์‚ฌ์šฉ๊ฐ€๋Šฅ.

์˜ˆ์ œ

๊ฒฝ์ฐฐ์„œ ๋ณ„๋กœ ๊ฐ€์žฅ ๋งŽ์ด ๋ฐœ์ƒํ•œ ๋ฒ”์ฃ„ ๊ฑด์ˆ˜์™€ ๋ฒ”์ฃ„ ์œ ํ˜•์„ ์กฐํšŒ.

mysql>select c.police_station, c.crime_type, c.case_number 
    ->from crime_status c, 
    ->(select police_station, crime_type, max(case_number) count 
    ->from crime_status where status_typ'๋ฐœ์ƒ' group by police_station) m  
    ->where c.police_station = m.police_station and c.case_number = m.count;

nested subquery

where ์ ˆ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ.

  • single row : ํ•˜๋‚˜์˜ ํ–‰์„ ๊ฒ€์ƒ‰ํ•˜๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ
  • multiple row : ํ•˜๋‚˜ ์ด์ƒ์˜ ํ–‰์„ ๊ฒ€์ƒ‰ํ•˜๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ
  • mutiple column : ํ•˜๋‚˜ ์ด์ƒ์˜ ์—ด์„ ๊ฒ€์ƒ‰ํ•˜๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ

single row subquery

์„œ๋ธŒ์ฟผ๋ฆฌ๊ฐ€ ๋น„๊ต์—ฐ์‚ฐ์ž์™€ ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ, ์„œ๋ธŒ์ฟผ๋ฆฌ์˜ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋Š” ํ•œ ๊ฐœ ํ–‰์˜ ๊ฒฐ๊ณผ๊ฐ’์„ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค.

์˜ˆ์ œ

snl์— ์ถœ์—ฐํ•œ ์…€๋Ÿฝ์ค‘์— id๊ฐ€ 1์ธ ์‚ฌ๋žŒ.

mysql> select name from celeb where name = (select host from snl_show where id = 1);

multiple row - IN

  • ์„œ๋ธŒ์ฟผ๋ฆฌ ์ถœ๋ ฅ๊ฒฐ๊ณผ์™€ ํ•˜๋‚˜๋ผ๋„ ์ผ์น˜ํ•˜๋ฉด ์ฐธ์ด ๋œ๋‹ค.

์˜ˆ์ œ

snl์— ์ถœ์—ฐํ•œ ์˜ํ™”๋ฐฐ์šฐ๋ฅผ ์กฐํšŒ

mysql> select host
    -> from snl_show
    -> where  host in (select name from celeb where job_title like '%์˜ํ™”๋ฐฐ์šฐ%');

multiple row - EXISTS

์˜ˆ์ œ

๋ฒ”์ฃ„ ๊ฒ€๊ฑฐ ํ˜น์€ ๋ฐœ์ƒ ๊ฑด์ˆ˜๊ฐ€ 2000๊ฑด๋ณด๋‹ค ํฐ ๊ฒฝ์ฐฐ์„œ ์กฐํšŒ

mysql> select name from police_station p where exists (select police_station from crime_status c where p.name = c.reference and case_number > 2000);

multiple row - ANY

์ปค๋ธŒ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ์ค‘์— ํ•˜๋‚˜๋ผ๋„ ๋งŒ์กฑํ•˜๋ฉด ๋จ

์˜ˆ์ œ

snl ์— ์ถœ์—ฐํ•œ ์ ์ด ์žˆ๋Š” ์—ฐ์˜ˆ์ธ ์ด๋ฆ„ ์กฐํšŒ

mysql> select name from celeb where name = any (select host from snl_show);

multiple row - ALL

์„œ๋ธŒ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๋ฅผ ๋ชจ๋‘ ๋งŒ์กฑํ•˜๋ฉด (๋น„๊ต์—ฐ์‚ฐ์ž ์‚ฌ์šฉ)

์˜ˆ์‹œ

mysql> select name from celeb 
    -> where name = all ( select host from snl_show where id = 1);

multi column subquery

์„œ๋ธŒ์ฟผ๋ฆฌ ๋‚ด์— ๋ฉ”์ธ์ฟผ๋ฆฌ ์ปฌ๋Ÿผ์ด ๊ฐ™์ด ์‚ฌ์šฉ๋˜๋Š” ๊ฒ…์šฐ

์˜ˆ์ œ

๊ฐ•๋™์›๊ณผ ์„ฑ๋ณ„, ์†Œ์†์‚ฌ๊ฐ€ ๊ฐ™์€ ์—ฐ์˜ˆ์ธ์˜ ์ด๋ฆ„, ์„ฑ๋ณ„, ์†Œ์†์‚ฌ๋ฅผ ์กฐํšŒ.

mysql> select name, sex, agency from celeb 
    -> where (sex, agency) in (select sex, agency from celeb where name='๊ฐ•๋™์›');
profile
๋‚˜๋Š” ๋ฌด์—‡์ด ๋ ๊ฒƒ์ธ๊ฐ€!!

0๊ฐœ์˜ ๋Œ“๊ธ€