PostgreSQL:循环直到条件为真

标签 postgresql loops while-loop postgresql-9.1

我正在尝试编写一个查询,该查询从指定值开始“循环”遍历数据库,直到条件为真。例如,假设我在 TABLE 示例中有以下条目:

id, parent, cond
1,        , True
2, 1      , False
3, 1      , False
4, 2      , False
... ... ...

我想要一个以输入(例如)4 为输入的查询,并将返回 2 和 1 的值。查询与 id 匹配的过程,如果 cond==False,将查看父级( id = 2).由于第二行中的 cond = False,因此将选择“parent”id (1)。现在看第一行,因为 cond=True,循环结束并返回 1 和 2。

我知道查询

SELECT parent FROM example WHERE id = 4;

将产生父 ID 2。

所以我徒劳地尝试创建一个循环:

WHILE (SELECT cond FROM example) = False
LOOP SELECT parent FROM example WHERE id = 4 
END LOOP;

首先,这会产生错误(“'while' 处或附近的语法错误”)。其次,我不知道如何在每次迭代后更新“id”。

在像 Python 这样的编程语言中,我可能会使用一个初始化为 4 的变量,然后在每次迭代时更新它……不确定如何在 Postgres 中做同样的事情。

如果您有任何问题或需要更多信息,请告诉我。谢谢!

最佳答案

你对SQL的想法是错误的。不要考虑循环、条件和变量;相反,请考虑如何描述您想要的数据。棘手的部分是您希望查询引用它自己的结果,这就是 recursive CTEs。用于:

The optional RECURSIVE modifier changes WITH from a mere syntactic convenience into a feature that accomplishes things not otherwise possible in standard SQL. Using RECURSIVE, a WITH query can refer to its own output.

您正在寻找这样的东西:

with recursive path as (
    select id, parent from T where id = 4
    union all
    select t.id, t.parent from T t join path p on t.id = p.parent
)
select id, parent
from path

这会给你这个:

 id | parent 
----+--------
  4 |      2
  2 |      1
  1 |       

然后您可以将它们放回数据库外部的一条路径中,该路径将更具链表性(或适合您的客户端语言的任何内容)。您当然不必包含 parent,但包含它会帮助您修复“指针”。

关于PostgreSQL:循环直到条件为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11840449/

相关文章:

python - 遍历 DictReader

python - matplotlib 在 while 循环中更新绘图,以日期为 x 轴

c++ - 用 while(cin >> x) 填充 std::vector<int> 的问题

PHP 是否可以在 while 循环中为每个 POST 表单发送唯一的值?

database - postgreSQL 错误 initdb : command not found

sql - Postgres : filtering results using ARRAY_AGG and HAVING (instead of WHERE)

sql - Postgres 在一个表上多次执行 JOIN

C++ QuickSort算法不断崩溃

postgresql - 动态查询postgres

c++ - 在switch语句中调用函数时,似乎永无休止的循环的问题(即使函数不包含循环)