2016-09-29 24 views
1

我有以下查詢,並且正在使用postgres插件ltree。我試圖做一些概念上類似於沿着你可以想象的樹的y軸切割樹的方法。僅使用ltree Postgres插件返回子結構

我可以很容易地用下面的查詢實現這個目標:

testdb2=# SELECT * FROM test WHERE yaxis >= 3 ORDER BY yaxis; 
       path    | yaxis | leaf 
--------------------------------+-------+------ 
Top.Hobbies.Amateurs_Astronomy |  3 | t 
Top.Science.Astronomy   |  3 | 
Top.Collections.Pictures  |  3 | 
Top.Hobbies     |  4 | 
Top.Science     |  4 | 
Top.Collections    |  4 | 
Top       |  5 | 

不過,我想一棵樹查詢不返回頁首,Top.Hobbies和Top.Science因爲有這些下面的節點。我明白說yaxis = 3會完成這個,但這組數據是過於簡化。

重要的一點是,這些不是葉子。下面有結構。所以我不在尋找返回葉子的東西。

這是全套:

     path      | yaxis | leaf 
-----------------------------------------------+-------+------ 
Top           |  5 | 
Top.Science         |  4 | 
Top.Science.Astronomy       |  3 | 
Top.Hobbies         |  4 | 
Top.Collections        |  4 | 
Top.Collections.Pictures.Astronomy   |  2 | 
Top.Collections.Pictures      |  3 | 
Top.Collections.Pictures.Astronomy.Stars  |  1 | t 
Top.Collections.Pictures.Astronomy.Galaxies |  1 | t 
Top.Collections.Pictures.Astronomy.Astronauts |  1 | t 
Top.Hobbies.Amateurs_Astronomy    |  3 | t 
Top.Science.Astronomy.Astrophysics   |  2 | t 
Top.Science.Astronomy.Cosmology    |  2 | t 

我想看到的值是這些:

   path    | yaxis | leaf 
--------------------------------+-------+------ 
Top.Hobbies.Amateurs_Astronomy |  3 | t 
Top.Science.Astronomy   |  3 | 
Top.Collections.Pictures  |  3 | 

但同樣,不使用值3精確匹配,因爲這個演示數據是過度簡化。

回答

1

有你的第一個查詢的結果,只要找到它的葉子:

with data(path) as (
-- select path from test where yaxis >= 3 
    values 
    ('Top.Hobbies.Amateurs_Astronomy'::ltree), 
    ('Top.Science.Astronomy'), 
    ('Top.Collections.Pictures'), 
    ('Top.Hobbies'), 
    ('Top.Science'), 
    ('Top.Collections'), 
    ('Top') 
) 
select * 
from data d1 
where not exists (
    select 1 
    from data d2 
    where d1.path <> d2.path 
    and d1.path @> d2.path); 

       path    
-------------------------------- 
Top.Hobbies.Amateurs_Astronomy 
Top.Science.Astronomy 
Top.Collections.Pictures 
(3 rows) 
+0

你這該死的都不錯。我需要變得更好。 –