기본 문법
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
Q1. 103번 보트를 예약한 적이 있는 선원의 이름 구하기
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND R.bid=103
Q4. 적어도 한 개의 배를 예약한 선원의 id
SELECT S.sid
FROM Sailors S, Reserves R
WHERE S.sid=R.sid
WHERE S.sname LIKE ‘B_%B’
↑ 여기 다시 보기
Q5. 빨간색이나 초록색 배를 예약한 선원의 id
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND (B.color=‘red’ OR B.color=‘
green’)
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘red’
UNION
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘
green’
Q6. 빨간색과 초록색 배를 모두 예약한 선원의 id
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘red’
INTERSECT
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color=‘
green’
중첩 쿼리
Q1. 103번 보트를 예약한 사람의 이름
SELECT S.sname
FROM Sailors S
WHERE S.sid IN (SELECT R.sid #IN은 앞이 뒤의 원소인지 아닌지 체크해주는 역할
FROM Reserves R
WHERE R.bid=103)
SELECT S.sname
FROM Sailors S
WHERE EXISTS (SELECT *
FROM Reserves R
WHERE R.bid=103 AND S.sid=R.sid)
SELECT S.sname
FROM Sailors S
WHERE S.sid (NOT) IN (SELECT R.sid
FROM Reserves R
WHERE R.bid IN ( SELECT B.bid
FROM Boats B
WHERE B.color =‘red’)
SELECT *
FROM Sailors S
WHERE S.rating > ANY (SELECT S2.rating
FROM Sailors S2
WHERE S2.sname=‘Horatio’)
Q6. 빨간색과 초록색 배를 모두 예약한 선원의 id
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’
AND S.sid IN (SELECT S2.sid
FROM Sailors S2, Boats B2, Reserves R2
WHERE S2.sid=R2.sid AND R2.bid=B2.bid
AND B2.color=‘green’)
Q9. 모든 배를 예약한 선원의 이름
SELECT S.sname
FROM Sailors S
WHERE NOT EXISTS
((SELECT B.bid
FROM Boats B)
EXCEPT
(SELECT R.bid
FROM Reserves R
WHERE R.sid=S.sid))
SELECT S.sname
FROM Sailors S
WHERE NOT EXISTS (SELECT B.bid
FROM Boats B
WHERE NOT EXISTS (SELECT R.bid
FROM Reserves R
WHERE R.bid=B.bid
AND R.sid=S.sid))
집계함수
선원들의 숫자
SELECT COUNT (*)
FROM Sailors S
등급이 10인 선원의 평균 나이
SELECT AVG ( DISTINCT S.age)
FROM Sailors S
WHERE S.rating=10
Group By 와 HAVING
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY grouping-list
HAVING group-qualification
SELECT S.rating, MIN (S.age)
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1 # 그룹화에 대한 조건
Null Values
OUTER JOIN
모든 데이터를 포함한다
매칭 되는 게 없는 건 null로
in == exists
not in != not exists