본 글은 아사이 아츠시 저 "하루 30분 36강으로 배우는 완전 초보의 SQL 따라잡기 SQL 첫걸음"을 기반으로 작성되었습니다.
delete from sample54 where a = (select min(a) from sample54);
서브쿼리의 패턴 4가지
select min(a) from sample54;
select no from sample54;
select min(a), max(no) from sample54;
select no, a from sample54;
이 중에서 1번 패턴을 스칼라 값을 반환하는 서브쿼리라고 한다.
select
(select count(*) from sample51) as sq1,
(select count(*) from sample54) as sq2
update sample54 set a = (select max(a) from sample54)
select * from (select * from sample54) sq
insert into sample542 select * from sample543
수정하려는 열의 개수와 자료형이 일치해야 한다.
update sample551 set a = 'exists'
where exists (select * from sample552 where no2 = no)
update sample551 set a = 'not exists'
where not exists (select * from sample552 where no2 = no)
select * from sample552 where no2 = no
와 같이 부모-자식 관계의 두 개의 테이블이 필요한 서브쿼리를 상관 서브쿼리라고 한다.
select * from sample551 where no in (3,5)
select * from sample551 where no in (select no2 from sample552)
주의할 점
IN 함수는 NULL과 비교를 수행할 수 없다.
https://www.hackerrank.com/challenges/challenges/problem
challenges
라는 이름의 문제로 해커랭크 사이트에서 가져왔다.
group by, join, sub query를 모두 물어보는 문제로 난이도가 꽤 있는 편이다.
select h.hacker_id, h.name, count(*) counter
from hackers h
inner join challenges c
on h.hacker_id = c.hacker_id
group by h.hacker_id, h.name
having (
counter = (select max(sub.cnt)
from (select count(*) cnt
from challenges
group by hacker_id) sub)
) or (
counter in (select sub.cnt
from(select count(*) cnt
from challenges
group by hacker_id) sub
group by sub.cnt
having count(*) = 1)
)
order by counter desc, h.hacker_id