'전체 글'에 해당되는 글 22건

  1. 2020.09.17 계층구조 테이블에서 계층쿼리 구현

Oracle의 계층형쿼리(Connect By Prior~)를 MySQL로 대체하여 표현해보자~

 

ex) 계층구조를 갖는 메뉴데이터를 계층쿼리로 표현

 

-------- 테이블 생성

CREATE TABLE 'tb_addr' (
    'a_idx' INT NOT NULL AUTO_INCREMENT COMMENT '주소번호',
    'a_pidx' INT NOT NULL COMMENT '부모 주소번호',
    'a_title' VARCHAR(100) NOT NULL COMMENT '주소명'
    PRIMARY KEY ('a_idx')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

-------- 쿼리(메뉴 계층구조 표현 및 정렬)

SELECT
  o_title, a_idx, IFNULL(lTB.a_pidx, 0) as a_pidx, IFNULL(cnt, 0) as sub_cnt, path
FROM(
  WITH RECURSIVE tmp1 AS
  (
      SELECT 
        a_idx, a_title, a_title as o_title, a_pidx, 
        a_title AS path,
        CONCAT(a_idx,',',a_title) AS sort_str,
        1 AS lvl
      FROM tb_addr WHERE a_pidx is null
      UNION ALL
      SELECT 
        e.a_idx, e.a_title, e.a_title as o_title, e.a_pidx, 
        CONCAT(t.path,'/',e.a_title) AS path, 
        CONCAT(t.sort_str,'>',CONCAT(e.a_idx,',',e.a_title)) AS sort_str, 
        t.lvl+1 AS lvl 
      FROM tmp1 t 
      JOIN tb_addr e 
      ON t.a_idx = e.a_pidx
  )
  SELECT 
    CONCAT(REPEAT(' ', lvl*4), a_title) as a_title, o_title,
    a_idx, a_pidx,
    path, sort_str, lvl
  FROM tmp1 
) lTB
LEFT JOIN(
  select a_pidx, count(a_pidx) as cnt from tb_addr group by a_pidx
) AS rTB
ON(lTB.a_idx = rTB.a_pidx)
ORDER BY sort_str

Posted by 셋부터넷
,