[SQL] With | JeongKeepsCalm

[SQL] With

With

1
2
3
4
5
6
7
8
9
10
11
with t1 as (
    select count(*) as cnt from kpa_cyberedu.educoursecreditsfo e
    where 1=1
        and e.lcnsNo = #{licenseNumber}
        and e.eduYear = #{eduYear}
)
select
    m.MBER_ID as memberId
    , t1.cnt as cnt
from mbertninfo m left join t1 on 1=1
where m.LCNS_NO = #{licenseNumber}

cnt 개수에 따라 로직처리 할 때 사용.

With Recursive

1
2
3
4
5
6
with recursive tableName as (
    select  ------------- A
    union all 
    select  ------------- B
)
select  ----------------- C

A: 재귀의 시작점이며 한 번만 실행이 된다.
B: 재귀적으로 실행이 되며 이전 단계의 결과를 사용하여 더 이상 결과가 생성되지 않을 때까지 새로운 결과를 생성한다. 새 결과의 행들이 테이블 하단에 추가된다.
C: 재귀쿼리가 다 실행된 후의 VIEW로부터 조회한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
-- 메뉴 뎁스 기준 재귀 쿼리
with recursive t3 as(
    select
        t1.id as menuId
        , t1.parent_id as parentMenuId
        , t1.name as menuName
        , t1.sort as sort
        , t1.used_at as usedAt
        , t1.depth as menuDepth
        , t1.url as menuUrl
    from menu t1
    where parent_id = 0
    union all
    select
        t2.id
        , t2.parent_id
        , CONCAT_WS(' > ', t3.menuName, t2.name)
        , t2.sort
        , t2.used_at
        , t2.depth
        , t2.url
    from menu t2 inner join t3 on t3.menuId = t2.parent_id
    )
    select
        t3.menuId
        , t3.parentMenuId
        , t3.menuName
        , t3.sort
        , t3.menuDepth
        , t3.menuUrl
    from t3
    where t3.usedAt = 'Y'
    order by t3.parentMenuId asc, t3.sort asc