[英]SQL Server query for tournament matches
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. 这个想法是,单个匹配可以来自零个父MatchID(在这种情况下,这是一次初始匹配/第一轮)或1或2个父MatchID。
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. 如果一场比赛只有1个父项MatchID,则意味着这场比赛是由与“再见”的人与先前参加比赛的人进行的。
IF a match has 2 parent MatchIDs that would mean that the match was generated with both people who previously competed. 如果一场比赛有2个双亲MatchID,则意味着这场比赛是由之前参加比赛的两个人共同产生的。
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 例如MatchID 1-> MatchID 5-> MatchID 7
Any help or suggestions would be great. 任何帮助或建议将是巨大的。 Thanks 谢谢
Common Table Expressions (CTE) fit best this task. 通用表表达式(CTE)最适合此任务。
;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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.