0

我需要在不同的表上编写一系列查询。它们都属于同一类型,一条记录有一个父记录,也可以有父记录。

我最终需要:

  1. 查找层次结构中的最高记录
  2. 查找层次结构中的最低点
  3. 找到所有的祖先
  4. 找到所有后代

我正在使用 Filemaker Pro,我不相信递归 SQL 查询可以在本地运行。有一些方法可以使用本机(递归)函数来实现所有 4 件事,这些函数可以填充实体(表)上的属性(字段),然后我可以查询这些属性(字段)。但是,我想了解 SQL 递归是如何工作的,看看我是否能找到一种更有效的方法来执行这些任务。

谢谢你的帮助!

4

1 回答 1

2

SQL recursion is not that common and many SQL dialects simply do not support it. FileMaker is one of them. Its SQL is fairly basic (e.g. it doesn't have LIMIT) and usually less efficient than native FileMaker approach (e.g. if you use an independent subquery, it still seems to run anew for each row in the main query). That is if you work with FileMaker and are interested in recursive SQL, it's bound to be a purely academic exercise. If you're after it, then this Wikipedia article on hierarchical and recursive SQL might be a good start.

But you don't need SQL for what you're trying to do; you can do all this with rather simple FileMaker calculations. Assuming your hierarchical table uses ID and Parent ID and two relationships, Parent and Child, create the following fields:

Root ID =
If( IsEmpty( Parent::ID ); ID; /* else */ Parent::Root ID )

Leaf IDs = 
If( IsEmpty( Child::ID ); ID; /* else */ List( Child::Leaf IDs ) )

Ancestor IDs =
List( Case( not IsEmpty( Parent::ID ); Parent::Ancestor IDs ); ID )

Descendant IDs =
List( ID; Case( not IsEmpty( Child::ID ); List( Child::Descendant IDs ) ) )

As you see each field has a recursive formula that refers to itself. You won't be able to enter it right after you add the field because by this time the field is not yet saved and FileMaker will complain that it cannot find it. To work around this first create a field, save it, and then edit it again and enter the formula.

于 2013-07-09T14:03:50.613 回答