1

我有以下查询,我正在使用 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 | 

但是,我想要一个不返回 Top、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 完全匹配,因为此演示数据过于简化。

4

1 回答 1

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)
于 2016-09-29T19:13:23.873 回答