KIC/DB 오라클

day08 - 오라클 (다중 컬럼, scalar sub query, inline view, exists 와 not exists)

바차 2021. 7. 10. 23:17
반응형

[다중 컬럼]

 

select empno, name, birthday, pay, position

from emp2

where (pay, position) in (select max(pay), position

                            from emp2 group by position);

 

 

 

select empno, name, birthday, pay, position from emp2

where pay = (select max(pay) from emp2 where position = e.position);

 

 

 

 

[scalar sub query(스칼라 서브쿼리)]

 

 

-> select 문에서 서브쿼리 추가

 

--emp2 deptno dept2 dcode 숫자 형식이 일치

select * from emp2;

select * from dept2;

-- 따라서 두 값을 비교해서 연결해준다.

select name, (select dname

from dept2 d

where e.deptno = d.dcode) – e. d.은 써주는 게 좋지만 두 테이블에 중복 없으면 오류x

from emp2 e;

 

 

 

 

[inline view (인라인 뷰)]

-> from 절에 테이블 대신 들어가는 것이 인라인 뷰

 

 

select d.dname 학과명,

s.max_height 최대키,

s.max_weight 최대몸무게

from (select deptno1, max(height) max_height, max(weight) max_weight

from student

group by deptno1) s, department d

where s.deptno1 = deptno;

 

 

 

 

--ex)

 

select rownum 순위, name, e.total

from student s, exam_01 e

where s.studno = e.studno -- rnum order by 해도 번호 순서가 유지된다.

order by 3; -- order by로 정렬 후에 rownum으로 순위를 매기고 싶은게 목적

 

select name, e.total

from student s, exam_01 e

where s.studno = e.studno

order by 2 desc; -- 이게 이제 인라인 뷰가 된다.

 

select rownum rnum, a.* from

(select name, e.total

from student s, exam_01 e

where s.studno = e.studno

order by 2 desc) a

where rownum between 3 and 5; -- 1일땐 출력 됨

-- 이게 3부터 시작하면 오류나는 이유는

--where 조건부터 적용되서 rownum이 안찍히기 때문

-- 따라서 sub qeury로 한번더 감싸줘서 where 조건을 걸어 출력해야한다.

 

 

 

-- 최종 정답

select rnum 순위, name 이름, total 점수 from (

select rownum rnum, a.* from

(select name, e.total

from student s, exam_01 e

where s.studno = e.studno

order by 2 desc) a)

where rnum between 3 and 5;

 

 

 

 

 

[exists not exists]

-> row의 존재를 물어보는 조건식

 

-- 해당 되는 서브 쿼리가 값이 존재하면 select 실행

select * from emp

where exists

(select 1 from emp where ename='FORD' and empno=333);

--1위치에 다른거 아무거나 넣어도 상관 없다. (의미 없음)

-- 서브 쿼리의 where문 조건이 타당한지만 확인하면 되기 때문

 

-- 해당 되는 서브 쿼리가 값이 없으면 select 실행

select * from emp

where not exists

(select 1 from emp where ename='FORD' and empno=333);

 

 

 

 

 

300x250