问题
How can I do a recursive self-join in SQL Server ? I have a table like this:
TableID | ParentID 1 | NULL 2 | 1 3 | 1 4 | 3 5 | NULL 6 | 4 7 | 6
I want to get the following results based on given TableID
to get all the ParentsID
related to the TableID
, let's say I want to get all the parents for the TableID = 6
:
TableID 6 4 3 1
I'm stuck on this and i don't know how to get the result in SQL Query ... Hope to tell me the SQL Query to get the previous data
回答1:
It should be
; WITH MyQuery (TableID, ParentID, Level) AS
(
SELECT M.TableID, M.ParentID, 0 AS Level
FROM MyTable M
WHERE M.TableID = 6 -- Here it's the row number where the query starts
UNION ALL
SELECT M.TableID, M.ParentID, Q.Level + 1
FROM MyTable M
INNER JOIN MyQuery Q ON M.TableID = Q.ParentID
)
SELECT * FROM MyQuery;
and as written by Byers, it's a Recursive Queries Using Common Table Expressions
The Level
column is useless (it isn't "useless useless". It's useless for what you asked), I have added it because it's quite often inserted in these recursive queries. If you don't need it, delete it from the 3 places it appears.
It seems to be much more complex to do the Level
in reverse (so that the grand-grand father is level 0, his childs are level 1...)
Note that this code will work with SQL Server >= 2005
来源:https://stackoverflow.com/questions/7780886/how-to-do-an-upper-recursive-self-join-in-sql-server