查询以获取递归定义的父级列表

塔伦

我正在尝试获取一个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)

但这不能正常工作,有什么建议吗?

杰罗姆·基迪克斯(Jerome Radix)

您必须小心要准确检索的内容。在这里,您需要一个包含所有祖先的表,因此创建时所用的表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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

递归搜索嵌套列表并获取父级

来自分类Dev

Laravel:获取嵌套列表雄辩递归的最后一个父级

来自分类Dev

Oracle CONNECT BY递归子级到父级查询,包括自我引用的最终父级

来自分类Dev

Oracle CONNECT BY递归子级到父级查询,包括自我引用的最终父级

来自分类Dev

SQL Server递归查询以显示父级路径

来自分类Dev

仅按父级排序的T-SQL递归查询

来自分类Dev

使用递归函数获取所有XElement父级

来自分类Dev

如何获取列表项以填充父级无序列表

来自分类Dev

如何获取列表项以填充父级无序列表

来自分类Dev

使用查询获取父级和子级数据

来自分类Dev

JQuery 在查询结果中获取元素的父级

来自分类Dev

如何获取每个treeview父级的子节点列表

来自分类Dev

递归Javascript:子级->父级关系

来自分类Dev

获取父级空白

来自分类Dev

获取父级的XPath

来自分类Dev

获取div的父级的父级

来自分类Dev

递归获取父div

来自分类Dev

父级列表中的列表

来自分类Dev

Oracle中的递归查询,直到层次结构中的父级满足条件为止?

来自分类Dev

sitecore查询以在多列表中为选定的父级选择子级

来自分类Dev

父级的JIRA按需查询

来自分类Dev

NHibernate父级列表与子级计数

来自分类Dev

Laravel获取父级属性

来自分类Dev

如何获取元素的父级

来自分类Dev

获取块设备父级

来自分类Dev

获取ToolStripDropDownMenu的(ToolStrip)父级

来自分类Dev

在父级之前获取元素

来自分类Dev

如何获取hasClass()的父级?

来自分类Dev

从 JSONObject 父级获取 JSONObject