Oracle SQL | View, Union

suyeon·2022년 4월 27일
0

Oracle SQL

목록 보기
1/6
post-thumbnail

220427

1. View, 뷰

  • DB Object 중 하나(테이블, 시퀀스, 제약사항, 뷰) -> 데이터베이스에 영구저장

  • 가상 테이블, 복사 테이블, 뷰 테이블 등..

  • 테이블처럼 사용한다 ★★★

  • 사용 용도 : query의 양을 줄이는 것이 목표

    • 반복된 SELECT or 긴 SELECT에 사용
    • 원본 테이블의 일부 필드나 일부 행만 필요할 때 사용
  • 읽기 전용 ★★★

  • 정의 : SQL(쿼리문)을 저장한 객체 ★★★

  • 뷰는 항상 원본 테이블을 실시간으로 읽어 동기화상태를 유지한다

  • 실제 데이터를 보유하지 않는 가짜이지만 테이블과 같은 자격을 가지며 테이블이 올 수 있는 모든 곳에 올 수 있다

CREATE VIEW 뷰이름
AS
SELECT;

뷰의 수정(or repalce)

  • 덮어씀
CREATE OR REPLACE VIEW 뷰이름
AS
SELECT;

ex) 비디오 가게 사장 > 하루 업무
     반복된 SELECT > 뷰 생성

create or replace view 대여체크
as
select
    m.name as mname,
    v.name as vname,
    to_char(r.rentdate,'yyyy-mm-dd') as rentdate,
    case
        when r.retdate is not null then '완료'
        else '미완료'
    end as state
from tblRent r
    inner join tblVideo v
        on v.seq = r.video
            inner join tblMember m
                on m.seq = r.member;


select * from 대여체크;

ex) tblInsa > 서울 직원 > view

create or replace view vwSeoul
as
select * from tblInsa where city = '서울'; 

select * from vwSeoul; -- 20명                               -- A. 실명. 이름이 있는 뷰 > 뷰
select * from (select * from tblInsa where city = '서울');   -- B. 익명. 이름이 없는 뷰 > 인라인 뷰

ex) 권한 > 계정별로 객체에 대한 접근/조작 등을 통제

select * from tblInsa;  -- 신입. tblInsa 접근권한 X
select * from 신입전용; -- 신입. view 접근권한 O


create or replace view 신입전용
as
select num, name, ssn, city from tblInsa;

뷰 사용

  • CRUD O -> R만 사용할 것
  1. INSERT > 실행 O > 절대 사용 금지

  2. SELECT > 실행 O > 뷰는 읽기 전용 테이블 ★★★

  3. UPDATE > 실행 O > 절대 사용 금지

  4. DELETE > 실행 O > 절대 사용 금지

2. Union

Join, Union 차이점

Join

  • 컬럼 + 컬럼

Union

  • 레코드 + 레코드

  • union : 합집합

  • intersect : 교집합

  • minus : 차집합

  • 전제조건 : 스키마 동일. 컬럼구조(자료형, 개수 일치)

-- A. 불가능
select * from tblCountry
union
select * from tblInsa;

-- B. 가능
-- 개수와 자료형이 같은 컬럼을 가져오면 union 연산 적용 가능 > but 의미 없는 데이터
select name, capital, population from tblCountry
union
select name, buseo, basicpay from tblInsa;

create table tblUnionA (
    name varchar2(30) not null
);


create table tblUnionB (
    name varchar2(30) not null
);

insert into tblUnionA values ('강아지'); -- @
insert into tblUnionA values ('고양이'); -- @
insert into tblUnionA values ('토끼');
insert into tblUnionA values ('거북이');
insert into tblUnionA values ('병아리');


insert into tblUnionB values ('강아지'); -- @
insert into tblUnionB values ('고양이'); -- @
insert into tblUnionB values ('호랑이');
insert into tblUnionB values ('사자');
insert into tblUnionB values ('코끼리');

-- union > 수학의 집합 개념 > 중복값 허용 X
select * from tblUnionA
union
select * from tblUnionB;

-- union all > 중복값 허용 O
select * from tblUnionA
union all
select * from tblUnionB;

-- intersect > 교집합
select * from tblUnionA
intersect
select * from tblUnionB;

-- minus > 차집합
select * from tblUnionA
minus
select * from tblUnionB;

select * from tblUnionB
minus
select * from tblUnionA;

0개의 댓글