ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 서브쿼리와 VIEW
    MySQL 2023. 1. 16. 14:55

    이번 게시글에서는 서브쿼리에 대해 추가로 학습하고, VIEW에 대해 알아보고자 한다.

    1. 스칼라 서브쿼리(Scalar subquery)

     

    select 절에 사용하는 서브쿼리로, 이름과 같이 서브쿼리의 값을 scalar(불연속)데이터로 반환하는 것을 말한다.

    예를 들자면, Orders 테이블에서 고객별 합산값을 도출하는데, custid 뒤에 이름을 표시하고 싶을 때에 다음과 같이 작성할 수 있다.

    select custid, (select name
                      from Customer cs
                      where cs.custid = od.custid) name
                 , sum(saleprice) total
      from Orders od
      group by custid;

    다음과 같이, 불연속형 데이터인 name을 서브쿼리 로 넣을 수 있다.

    하지만 이 방법은 다음과 같이 inner join으로 대체 가능하므로, 자주 쓰이지 않는다.

     

    select a.custid, b.name, sum(a.saleprice) total
      from Orders a, Customer b 
      where a.custid = b.custid
      group by custid;

     

    2. 인라인 뷰(Inline view)

     

    인라인 뷰는 FROM절에서 사용되는 서브쿼리로, 가상의 테이블을 생성하는 것이다.

    custid가 2이하인 고객의 정보를 저장할 때, 다음과 같이 설정할 수 있다.

    selet cs.custid
      from Customer cs
      where custid <= 2;

    이를 from절에 사용함으로써 다음 문장에서 custid가 2 이하인 고객만 결과를 도출할 수 있다.

    select a.custid, a.name, od.saleprice
      from (select custid, name
                 from Customer
                 where custid <= 2) a,
           Orders od
      where a.custid = od.custid;

    3.VIEW

     

    뷰는 inline view보다 더 본격적인 임시 테이블의 느낌으로, 특정 결괏값을 가상의 테이블로 저장해두는 것을 말한다.

    뷰 또한 테이블처럼 create문을 사용하며, 이와 같은 형식이다.

    create view _(view이름)_
    as
    (이하 select 문)

     

    예시를 들어보자.

    ​​

    Q. 주문번호, 고객번호, 고객이름, 도서번호, 도서이름, 판매금액을 자주 사용하다 보니, view로 만들어두고자 한다.

    create view V_Orders
    as
    select od.orderid, od.custid, cs.name, bk.bookid, bk.bookname, od.saleprice
      from Orders od, Customer cs, Book bk
      where cs.custid = od.custid and bk.bookid = od.bookid;

    확인을 위해 다음과 같이 코드를 입력하면,

    select * 
      FROM V_Orders

    다음과 같이 나온다.

    'MySQL' 카테고리의 다른 글

    데이터 순번 매기기 · UPDATE 함수  (0) 2023.01.16
    MySQL 내장 함수  (0) 2023.01.16
    ALTER문으로 테이블 컨트롤하기  (0) 2023.01.11
    CASE로 조건 설정하기  (0) 2023.01.11
    서브쿼리와 EXISTS  (0) 2023.01.10

    댓글

Designed by Tistory.