I've got a database that manages files - some files contain/reference other files, and my goal is to design a query that can give me the whole "tree" for a given document.
For example the structure may look like this:
- File 1
- File 2
- File 3
- File 4
- File 5
- File 6
- File 7
- File 8
- File 9
- File 10
etc., where File 1 effectively contains all of the files following it
These are broken out in my database between two tables - lets call them the "Files" table and the "References" table
The "Files" table has information about the files themselves - FileID, Filename, etc.
The "References" table shows the relationship of the above structure using the FileIDs of the files. My issue is that, for example, File 6 is not referenced by File 1 - it is only referenced by File 5.
e.g.:
[ParentFileID] [ChildFileID]
1 2
1 3
1 4
1 5
5 6
5 7
5 8
8 9
8 10
Ideally I'd like to be able to check the position in the entire structure for any given FileID I pass in
Any ideas? I've been reading up on CTEs and it feels like some sort of recursive common table expression is what I'm after, though every example I can find is using one table and involves NULLs to track down the top level elements.