I have a table for storing matches (games or whatever you want to call them) for the purpose of being able to view a bracket for a single division.
Here's the table:
CREATE TABLE [dbo].[Match]
(
[MatchID] [bigint] IDENTITY(1,1) NOT NULL,
[OrgDivisionID] [bigint] NOT NULL,
[MatchTimeLength] [bigint] NULL,
[ParentMatchID1] [bigint] NULL,
[ParentMatchID2] [bigint] NULL,
CONSTRAINT [PK_Match]
PRIMARY KEY CLUSTERED ([MatchID] ASC)
)
Sample Data:
MatchID OrgDivisionID MatchTimeLength ParentMatchID1 ParentMatchID2
----------------------------------------------------------------------
1 1 180 NULL NULL
2 1 180 NULL NULL
3 1 180 NULL NULL
4 1 180 NULL NULL
5 1 180 1 2
6 1 180 3 4
7 1 180 5 6
(The details of who or what team is involved in a match will be stored in a separate table which is not relevant now.)
The idea is that, a single match can come from zero parent MatchIDs (in that case it is a initial matches/first round) OR 1 or 2 parent MatchIDs.
IF a match has only 1 parent MatchID that would mean that the match was generated with a person who had a "bye" vs a person who previously competed.
IF a match has 2 parent MatchIDs that would mean that the match was generated with both people who previously competed.
What I need help with is a query that will show the full path of all the matches. For example MatchID 1 -> MatchID 5 -> MatchID 7
Any help or suggestions would be great. Thanks
Common Table Expressions (CTE) fit best this task.
;with cte as (
--anckor query
select MatchID,ParentMatchID1,ParentMatchID2, 1 lvl
from #match
where matchid = 1 --or other id
union all -- note: UNION ALL
--recursive query
select m.MatchID,m.ParentMatchID1,m.ParentMatchID2, lvl+1
from #match m
inner join cte on cte.matchid = m.ParentMatchID1 or cte.matchid = m.ParentMatchID2
)
--Get result from here
select * from cte
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.