Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 河网查询_Sql_Hierarchy - Fatal编程技术网

Sql 河网查询

Sql 河网查询,sql,hierarchy,Sql,Hierarchy,我在SQL中有下表: RiverID | RiverName | RecipientID ------------------------------------ 0 | Atlantic Ocean | NULL 1 | Mississippi | 0 2 | Missouri | 1 3 | Yellowstone | 2 4 | Bighorn | 3 5 | Wind

我在SQL中有下表:

RiverID | RiverName      | RecipientID
------------------------------------
0       | Atlantic Ocean | NULL
1       | Mississippi    | 0
2       | Missouri       | 1
3       | Yellowstone    | 2
4       | Bighorn        | 3
5       | Wind           | 3
表中的RecipientID表示:如果为空,则表行表示海洋或封闭的流域。如果RecipientID不为NULL,则它是一条河流,与下游的另一条河流汇合

现在我想提出一个问题:给定一条河流,找到所有下游河流,直到你到达大海。例如:给定河流“风”(RiverID=5),查询结果将显示:

Wind - Yellowstone - Missouri - Mississippi - Atlantic Ocean.

如何用SQL编写此查询?

并非所有SQL数据库都支持分层查询。当他们这样做时,语法通常是不同的

如果系统中的链接数达到最大值,则可以使用连接执行所需的操作:

select r.RiverName, r1.RiverName, r2.RiverName, r3.RiverName, r4.RiverName, r5.RiverName
from rivers r left outer join
     rivers r1
     on r.RecipientId = r1.RiverId left outer join
     rivers r2
     on r1.RecipientId = r2.RiverId left outer join
     rivers r3
     on r2.RecipientId = r3.RiverId left outer join
     rivers r4
     on r3.RecipientId = r4.RiverId left outer join
     rivers r5
     on r4.RecipientId = r5.RiverId ;

这将名称放在五个单独的列中。您可以将它们连接在一起,将它们放在一列中。

一个序列中河流的最大数量是多少?您使用的数据库是什么?它必须是纯SQL吗?您是否可以使用TSQL/PLSQL(如Gordon所问,取决于哪个数据库)?如果您可以使用其他编程语言,可能会使问题变得更容易。老实说,我会在这里使用
光标
,因为您不知道需要多少次迭代。在我看来,它也更具可读性。我目前正在使用MicrosoftSQLServer2008。当前最大链接数(从河流开始到海洋)为10。系统中的最大链接数当前为10,但随着新数据添加到数据库中,链接数可能会增加。但我不认为从任何一条河流到海洋的连接线都会超过20条。使用的平台是MicrosoftSQLServer2008。