我一直在努力为Postgres 9.4中的一个表提供SQL查询。该表是典型的相邻模型:
Table: categories
id | code | parent_id
----+------+-----------
1 | la |
2 | wst | 1
3 | sfv | 1
4 | lac | 1
5 | sgv | 1
6 | lgb | 1
7 | ant | 1
8 | sf |
9 | sfc | 8
10 | sby | 8
11 | eby | 8
12 | pen | 8
13 | nby | 8
14 | scz | 8
我需要一个查询,它将返回:
a)顶级类别的子ID列表(例如
la
,sf
)或b)如果搜索的类别已经是子类别(例如
wst
,sfv
等),则它自己的id。换句话说:
select id ... where categories.id=1 // => 2,3,4,5,6,7
select id ... where categories.id=2 // => 2
select id ... where categories.id=3 // => 3
... ... ...
select id ... where categories.id=8 // => 9,10,11,12,13,14
select id ... where categories.id=9 // => 9
select id ... where categories.id=10 // => 10
... ... ...
我已经接近了,但还不能确定。非常感谢你的帮助。谢谢您。
最佳答案
您需要将Id
传递到Id
和Parent_Id
列。试试这个。
SELECT *
FROM category
WHERE ( id = 1
OR parent_id = 1 )
AND parent_id IS NOT NULL
考虑到
Parent_Id
是一个integer
列,并且当aId
是父列时,parent_id
列将NULL
SQLFIDDLE DEMO