Question

I have the following table in SQL:

RiverID | RiverName      | RecipientID
------------------------------------
0       | Atlantic Ocean | NULL
1       | Mississippi    | 0
2       | Missouri       | 1
3       | Yellowstone    | 2
4       | Bighorn        | 3
5       | Wind           | 3

RecipientID in my table means: If it's NULL then the table row represents an ocean or a closed drainage basin. If RecipientID is not NULL then it is a river that joins another river downstream.

Now I want to make a query: Given a river, find all rivers downstream until you reach the ocean. For example: Given the river "Wind" (RiverID=5) the query result would show:

Wind - Yellowstone - Missouri - Mississippi - Atlantic Ocean.

How do I write this query in SQL?

Was it helpful?

Solution

Not all SQL databases have support for hierarchical queries. And when they do, the syntax is often different.

If you have a maximum number of links in the system, then you can do what you want with joins:

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 ;

This puts the names in five separate columns. You can concatenate them together to put them in a single column.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top