PostgreSQL 將父子表按照父子結構排序
阿新 • • 發佈:2018-12-12
示例:
WITH RECURSIVE T ( yhlxid, yhlxtitle, yhlxpid, PATH, DEPTH, showindex ) AS ( SELECT yhlxid, yhlxtitle, yhlxpid, '' || yhlxid :: VARCHAR AS PATH, 1 AS DEPTH, showindex FROM gc_curing_yhlx WHERE 1 = 1 AND yhlxtype = 'curing' UNION ALL SELECT D.yhlxid, D.yhlxtitle, D.yhlxpid, T.PATH || '/' || D.yhlxid, T.DEPTH + 1 AS DEPTH, D.showindex FROM gc_curing_yhlx D JOIN T ON D.yhlxpid = T.yhlxid ) SELECT yhlxid, yhlxtitle, yhlxpid, PATH, DEPTH, showindex FROM T ORDER BY PATH, showindex;
進階,組合排序:
WITH RECURSIVE T ( yhlxid, yhlxtitle, yhlxpid, PATH, DEPTH, showindex ) AS ( SELECT yhlxid, yhlxtitle, yhlxpid, '' || yhlxid :: VARCHAR AS PATH, 1 AS DEPTH, showindex FROM gc_curing_yhlx WHERE 1 = 1 AND yhlxtype = 'curing' UNION ALL SELECT D.yhlxid, D.yhlxtitle, D.yhlxpid, T.PATH || '/' || D.showindex || D.yhlxid, T.DEPTH + 1 AS DEPTH, D.showindex FROM gc_curing_yhlx D JOIN T ON D.yhlxpid = T.yhlxid ) SELECT yhlxid, yhlxtitle, yhlxpid, PATH, DEPTH, showindex FROM T ORDER BY PATH, showindex;