0

我有一张桌子:

CREATE TABLE cell
(
  cellpk serial NOT NULL,
  cellname character varying NOT NULL,  
  parent integer NOT NULL,
  CONSTRAINT cellpk PRIMARY KEY (cellpk)
)
单元格A --> 子单元格A1 --> 子子单元格A1
      |--> subcellA2 --> subsubcellA2   

我想在同一行中获取单元格及其父级的名称。

就像是-

亚细胞A1 - 细胞A
亚细胞A2 - 细胞A
subsubcellA1- subcellA1
subsubcellA2- subcellA2

我有一个查询,它给出了父 ID 而不是单元名称。我怎样才能得到父母的名字而不是身份证。

WITH RECURSIVE cell_child as
(
SELECT fp.* FROM cell as fp WHERE fp.parent = '111'
 UNION ALL
 SELECT f.*
   FROM
     cell as f
 JOIN cell_child as fc
 ON (f.parent = fc.cellpk)     
 )     
 select * from cell_child as cc
4

1 回答 1

0

尝试加入原始表:

WITH RECURSIVE cell_child AS (
  SELECT fp.* FROM cell as fp WHERE fp.parent = '111'
  UNION ALL
  SELECT f.* FROM cell AS f
    JOIN cell_child as fc ON f.parent = fc.cellpk
 )     
 SELECT cc.*, parent.cellname
   FROM cell_child AS cc
   LEFT JOIN cell AS parent ON parent.cellpk = cc.parent;
于 2012-05-23T19:02:21.787 回答