我有以下查询,我使用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完全匹配,因为这个演示数据是一个过度简化。
发布于 2016-09-29 19:13:23
有了第一个查询的结果,只需在其中找到叶子:
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)https://stackoverflow.com/questions/39776945
复制相似问题