SQL 첫걸음 23-24강

Andrew·2022년 1월 12일
0

SQL 첫걸음

목록 보기
6/9

본 글은 아사이 아츠시 저 "하루 30분 36강으로 배우는 완전 초보의 SQL 따라잡기 SQL 첫걸음"을 기반으로 작성되었습니다.

23강

서브쿼리

DELETE의 WHERE 구에서 서브쿼리

delete from sample54 where a = (select min(a) from sample54);

스칼라 값을 반환하는 서브쿼리

서브쿼리의 패턴 4가지

  1. 스칼라 값 반환
select min(a) from sample54;
  1. 하나의 열, 복수 행
select no from sample54;
  1. 하나의 행, 복수 열
select min(a), max(no) from sample54;
  1. 복수 행, 복수 열
select no, a from sample54;

이 중에서 1번 패턴을 스칼라 값을 반환하는 서브쿼리라고 한다.

SELECT 구에서 서브쿼리

select 
	(select count(*) from sample51) as sq1,
    	(select count(*) from sample54) as sq2

SET 구에서 서브쿼리

update sample54 set a = (select max(a) from sample54)

FROM 구에서 서브쿼리

select * from (select * from sample54) sq

INSERT 명령과 서브쿼리

insert into sample542 select * from sample543

수정하려는 열의 개수와 자료형이 일치해야 한다.

24강

상관 서브쿼리

(NOT) EXISTS

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 와 같이 부모-자식 관계의 두 개의 테이블이 필요한 서브쿼리를 상관 서브쿼리라고 한다.

(NOT) IN

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를 모두 물어보는 문제로 난이도가 꽤 있는 편이다.

SQL 정답 코드

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
profile
조금씩 나아지는 중입니다!

0개의 댓글