예시) '대한민국'에 거주하는 고객의 이름과 주소를 출력합니다. 출력결과에 행 번호를 붙입니다.
select rownum, name, address
from customer
where address like '대한민국%';
예시) '대한민국'에 거주하는 고객의 이름과 주소를 행번호를 붙여 앞에서 2명만 출력
select rownum no, name, address
from customer
where address like '대한민국%' and rownum <= 2;
예시) 고객번호로 내림차순으로 정렬하여 고객번호와 이름을 순번을 붙여 출력
select rownum, custid, name
from (select custid, name
from customer
order by custid desc);
==> order by 한 쿼리문을 from절 안에 넣어주면 order by가 먼저 실행하게 된다.
예시) 고객이름 별로 판매액을 출력
select (select name
from customer c
where c.custid = o.custid) name, sum(saleprice) total
from orders o
group by custid;
==> 서브쿼리에 조건식이 메인쿼리와 조건식이 있어서 join이라고 생각할 수 있는데 이 경우 조인이라고 하지 않고 '상관 서브쿼리' 라고 한다.
예시) 고객번호가 2 이하인 고객들에 대하여 고객 이름별로 총 판매액을 출력
select name, sum(saleprice)
from (select custid, name
from customer
where custid <= 2) c, orders o
where c.custid = o.custid
group by name;
다중행 연산자에 대하여 설명하세요.
===> 서브쿼리가 where절에 사용될 때에 서브쿼리의 건수가 여러 건일 떄 사용하는 연산자이면 [in, not in, all, some, any] 등이 있다.
<단일 연산자>
예시) '대한민국'에 거주하는 고객에게 판매한 도서의 총 판매금액을 출력
select sum(saleprice)
from orders
where custid = (select custid
from customer
where name = '박지성');
==> 이 때 서브쿼리의 건수는 1건이기 때문에 = 연산자를 사용할 수 있다.
<다중행 연산자>
select sum(saleprice)
from orders
where custid in (select custid
from customer
where address like '%대한민국%');
==> 서브쿼리의 건수가 여러 건이기 때문에 = 연산자는 사용할 수 없고, in 연산자를 사용해야 한다.
예시)
select orderid, saleprice
from orders
where saleprice > all (select saleprice from orders where custid = 3);
예시) exists 연산자를 이용하여 대한민국에 거주하는 고객에게 판매한 도서의 총 판매액을 출력
select sum(saleprice)
from orders o
where exists (select * from customer c
where address like '%대한민국%' and c.custid = o.custid);
<기본문법>
create view 뷰이름 [(열이름 [,...])]
as select문
예제) '축구' 관련 도서를 검색하는 뷰를 생성
create view vw_book
as select * from book where bookname like '%축구%';
<기본문법>
create view 뷰이름 as select절
조건식 with check option;
예시) with check option을 넣어 뷰 생성하기
create view vw_emp_20 as
select eno, ename, dno, phone, addr
from emp
where dno = 20
with check option;
<기본문법>
create view 뷰이름 as select with read only;