0

I have a table:

CREATE TABLE cell
(
  cellpk serial NOT NULL,
  cellname character varying NOT NULL,  
  parent integer NOT NULL,
  CONSTRAINT cellpk PRIMARY KEY (cellpk)
)
cellA --> subcellA1 --> subsubcellA1
      |--> subcellA2 --> subsubcellA2   

I want to get the cell and its parent's name in the same row.

Something like-

subcellA1   -    cellA
subcellA2   -    cellA
subsubcellA1-    subcellA1
subsubcellA2-    subcellA2

I have a query which gives the parent id instead of the cellname. How can I get the parent's name instead of the 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
vyegorov
  • 21,787
  • 7
  • 59
  • 73
blue01
  • 2,035
  • 2
  • 23
  • 38

1 Answers1

0

Try joining to the original table:

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;
vyegorov
  • 21,787
  • 7
  • 59
  • 73