简体   繁体   中英

XQuery: if condition inside a double for

I'm trying to update a $numMatches variable inside an if statement, inside a double for, to keep track of the matches played by the teams in an XML document. The code raises an error.

The pseudo logic is:

"For each team in teams, for each match played, if the team's id is equal to the local or visitor player, add 1 to the number of matches played by that team".

The XQuery I tried is:

<resumen>    
{ for $teams in ligue/teams/team

    let $numMatches := 0

    for $matches in ligue/match_results/match

        if ($teams/team_id = $matches/local) or ($teams/team_id = 
        $matches/visitor) then

        $numMatches := $numMatches + 1

    return <teamAndMatches>{$teams/name/data()}-{$numMatches}</teamAndMatches>   
}
</resumen>

There is an error there, as XBase says it expects a return. Where is the error? I'm new to this language. Thanks!

XQuery (XML Query) is a query and functional programming language that queries and transforms collections of structured and unstructured data, usually in the form of XML, text and with vendor-specific extensions for other data formats (JSON, binary, etc.).

quoted from the WikiPedia XQuery article .

XQuery is a functional programming language, which implies variables are immutable.

quoted from this SO answer .

So you cannot update your variable like this

$numMatches := $numMatches + 1

because the variable is immutable.
You were thinking from an imperative paradigm which doesn't apply here.

If you want to solve this riddle, try thinking from a functional paradigm and reprogram this function recursively (which probably means passing the counters as parameters to the recursive function).

There is a count function so doing

<resumen>    
{ for $teams in ligue/teams/team

    return <teamAndMatches>{$teams/name/data()}-{count(ligue/match_results/match[local = $teams/team_id or visitor = $teams/team_id])}</teamAndMatches>   
}
</resumen>

should suffice.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM