我正在尝试获取一个ID列表,其中包含给定记录的所有父代的ID。
表格:carrier_products(id,carrier_product_id)
到目前为止,我已经提出了
carrier_products.id IN
(WITH RECURSIVE tree(id, carrier_product_id) AS (
SELECT cp.id, cp.carrier_product_id FROM carrier_products cp WHERE cp.id = ?
UNION
SELECT cp.id, cp.carrier_product_id
FROM carrier_products cp JOIN tree ON cp.carrier_product_id = tree.id
)
SELECT id FROM tree)
但这不能正常工作,有什么建议吗?
您必须小心要准确检索的内容。在这里,您需要一个包含所有祖先的表,因此创建时所用的表WITH RECURSIVE
应该只有一个字段(id
)。另外,请注意递归的结束条件(null
价值测试)。这是一个解决方案:
postgres@localhost testdb=# create table carrier_products(id integer unique not null, carrier_product_id integer);
CREATE TABLE
Temps : 33,361 ms
postgres@localhost testdb=# insert into carrier_products(id, carrier_product_id) values (0, null);
INSERT 0 1
Temps : 3,005 ms
postgres@localhost testdb=# insert into carrier_products(id, carrier_product_id) values (1, 0);
INSERT 0 1
Temps : 1,151 ms
postgres@localhost testdb=# insert into carrier_products(id, carrier_product_id) values (2, 0);
INSERT 0 1
Temps : 0,978 ms
postgres@localhost testdb=# insert into carrier_products(id, carrier_product_id) values (3, 1);
INSERT 0 1
Temps : 0,676 ms
postgres@localhost testdb=# select * from carrier_products;
id | carrier_product_id
----+--------------------
0 | NULL
1 | 0
2 | 0
3 | 1
(4 lignes)
postgres@localhost testdb=# WITH RECURSIVE tree(id) AS (
SELECT cp.carrier_product_id FROM carrier_products cp WHERE cp.id = 3
UNION
SELECT cp.carrier_product_id
FROM carrier_products cp JOIN tree ON cp.id = tree.id and cp.carrier_product_id is not null
)
SELECT id FROM tree;
id
----
1
0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句