xQuery如何在多个for循环中对结果进行排序

时间:2013-12-18 15:51:46

标签: xml xsd xquery

首先,对于误导性的标题感到抱歉,我在制定这个问题时遇到了麻烦。

使用以下XML文件,其中包含有关不同玩家,不同团队以及最后两个玩家团队之间关系的一些信息。

<Ligue>
    <Players>
        <Player>
            <PlayerId>1</PlayerId>
            <PlayerName>Johnson</PlayerName>
            <PlayerFirstName>Steven</PlayerFirstName>
        </Player>

        <Player>
            <PlayerId>2</PlayerId>
            <PlayerName>Bob</PlayerName>
            <PlayerFirstName>Billy</PlayerFirstName>
        </Player>

        <Player>
            <PlayerId>3</PlayerId>
            <PlayerName>Smith</PlayerName>
            <PlayerFirstName>John</PlayerFirstName>
        </Player>
    </Players>

    <Teams>
        <Team>
            <TeamId>1</TeamId>
            <TeamName>The super Zubats</TeamName>
        </Team>

        <Team>
            <TeamId>2</TeamId>
            <TeamName>The diglets trio</TeamName>
        </Team>
    </Teams>

    <PlayerTeams>
        <PlayerTeam>
            <PlayerId>1</PlayerId>
            <TeamId>1</TeamId>
            <DateBegin>2013-12-01</DateBegin>
            <DateEnd></DateEnd>
            <Number>69</Number>
        </PlayerTeam>

        <PlayerTeam>
            <PlayerId>1</PlayerId>
            <TeamId>2</TeamId>
            <DateBegin>2013-01-10</DateBegin>
            <DateEnd>2013-11-20</DateEnd>
            <Number>69</Number>
        </PlayerTeam>

        <PlayerTeam>
            <PlayerId>2</PlayerId>
            <TeamId>2</TeamId>
            <DateBegin>2013-01-10</DateBegin>
            <DateEnd></DateEnd>
            <Number>12</Number>
        </PlayerTeam>

        <PlayerTeam>
            <PlayerId>3</PlayerId>
            <TeamId>2</TeamId>
            <DateBegin>2013-01-10</DateBegin>
            <DateEnd></DateEnd>
            <Number>73</Number>
        </PlayerTeam>
    </PlayerTeams>
</Ligue>

我在这里要做的是用Xquery找到每个队员中的球员。最后,我需要列出一个团队及其中的每个玩家。不幸的是,我是Xquery的新手,而我所要做的就是将每个玩家列入他所参与的团队,并使用以下代码

for $b in doc("ligue.xml")/Ligue/Teams/Team,
    $c in doc("ligue.xml")/Ligue/PlayerTeams/PlayerTeam,
    $d in doc("ligue.xml")/Ligue/Players/Player
            where $c/TeamId = $b/TeamId and empty($c/DateEnd) and $c/PlayerId = $d/PlayerId
                return <Team>{$b/TeamName,<Player>{string($d/PlayerFirstName), string($d/PlayerName)}</Player>}</Team>

这给我一个像这样的结果

<?xml version="1.0" encoding="UTF-8"?>
<Team>
    <TeamName>The super Zubats</TeamName>
    <Player>Steven Johnson</Player>
</Team>

我想知道是否有人能给我一个如何实现我的目标的暗示。我尝试使用“let”但我似乎不明白如何正确使用它。

1 个答案:

答案 0 :(得分:2)

首先对球队进行迭代,然后加入球员和球员队伍:

for $team in doc("ligue.xml")/Ligue/Teams/Team
  return 
    <Team>
       {$team/TeamName}
       {for $player in doc("ligue.xml")/Ligue/Players/Player, 
            $playerTeam in doc("ligue.xml")/Ligue/PlayerTeams/PlayerTeam
          where $player/PlayerId = $playerTeam/PlayerId and $playerTeam/TeamId = $team/TeamId
          return $player}
   </Team>

我希望这个查询是自我解释的,但如果没有添加评论:)