递归SQL PostgreSQL空结果集

时间:2013-02-13 21:34:02

标签: postgresql recursion null resultset adjacency-list

类别表:

=# \d
          List of relations
 Schema |    Name     | Type  | Owner
--------+-------------+-------+-------
 public | categories  | table | pgsql
 public | products    | table | pgsql
 public | ticketlines | table | pgsql
(3 rows)

类别内容:

=# select * from categories;
 id |  name  | parentid
----+--------+----------
 1  | Rack   |
 2  | Women  | 1
 3  | Shorts | 2
 4  | Wares  |
 5  | Toys   | 4
 6  | Trucks | 5
(6 rows)

运行以下查询:

WITH RECURSIVE nodes_cte(name, id, parentid, depth, path) AS (
-- Base case?
 SELECT c.name, 
  c.id, 
  c.parentid, 
  1::INT AS depth, 
  c.id::TEXT AS path 
 FROM categories c
 WHERE c.parentid = ''
UNION ALL
-- nth case
 SELECT c.name, 
  c.id, 
  c.parentid, 
  n.depth + 1 AS depth, 
  (n.path || '->' || c.id::TEXT) 
 FROM nodes_cte n
  JOIN categories c on n.id = c.parentid
)
SELECT * FROM nodes_cte AS n GROUP BY n.name, n.id, n.parentid, n.depth, n.path ORDER BY n.id ASC
;

得出这些结果:

  name  | id | parentid | depth |  path
--------+----+----------+-------+---------
 Rack   | 1  |          |     1 | 1
 Women  | 2  | 1        |     2 | 1->2
 Shorts | 3  | 2        |     3 | 1->2->3
 Wares  | 4  |          |     1 | 4
 Toys   | 5  | 4        |     2 | 4->5
 Trucks | 6  | 5        |     3 | 4->5->6
(6 rows)

大!

但是给出了类似的表格(类别):

=# \d categories
        Table "public.categories"
  Column  |       Type        | Modifiers
----------+-------------------+-----------
 id       | character varying | not null
 name     | character varying | not null
 parentid | character varying |
 image    | bytea             |
Indexes:
    "categories_pkey" PRIMARY KEY, btree (id)
    "categories_name_inx" UNIQUE, btree (name)
Referenced by:
    TABLE "products" CONSTRAINT "products_fk_1" FOREIGN KEY (category) REFERENCES categories(id)

=# select * from categories;
                  id                  | name  |               parentid               | image
--------------------------------------+-------+--------------------------------------+-------
 611572c9-326d-4cf9-ae4a-af5269fc788e | Rack  |                                      |
 22d15300-40b5-4f43-a8d1-902b8d4c5409 | Women | 611572c9-326d-4cf9-ae4a-af5269fc788e |
 6b061073-96f4-49a1-9205-bab7c878f0cf | Wares |                                      |
 3f018dfb-e6ee-40d1-9dbc-31e6201e7625 | Toys  | 6b061073-96f4-49a1-9205-bab7c878f0cf |
(4 rows)

相同的查询产生零行。

为什么?

是否与主键/外键有关?

1 个答案:

答案 0 :(得分:1)

WHERE COALESCE(parent_id, '') = ''

的工作。谢谢。