2013-02-13 97 views
0

类别表:类别递归SQL PostgreSQL的查询结果为空

=# \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) 

相同的查询产生零行。

为什么?

这是与主/外键有关吗?

+0

parentid'NULL'而不是空字符串?尝试将'parentid ='''更改为'parentid = IS NULL'。 – 2013-02-13 21:37:14

+0

也许你在查询中没有显示错误? – wildplasser 2013-02-13 21:37:27

+0

丹尼尔的想法很可能是正确的,但查询应该是“parentid is null”,没有“=”。 – 2013-02-13 21:40:56

回答

1
WHERE COALESCE(parent_id, '') = '' 

工作。谢谢。