我有以下查询,并且我使用了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精确匹配,因为这个演示数据过度简化。
答案 0 :(得分: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)