Return 仅使用 ltree Postgres 插件的子结构

Return only substructure using ltree Postgres plugin

我有以下查询并且我正在使用 postgres 插件 ltree。我正在尝试做一些概念上类似于沿着您可以想象的树的 y 轴切割树的事情。

我可以使用以下查询轻松完成此操作:

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 | 

但是我想要一个没有 return Top、Top.Hobbies 和 Top.Science 的树查询,因为它们下面有节点。我知道说 yaxis=3 可以实现这一点,但是这组数据过于简单化了。

重要的一点是这些不是树叶。下面有结构。所以我不是在寻找 returns 留下的东西。

这是全套:

                     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 完全匹配,因为这个演示数据过于简单化了。

有了第一个查询的结果,只需找到其中的叶子即可:

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)