【问题标题】:XQuery join resultXQuery 连接结果
【发布时间】:2016-03-14 12:38:42
【问题描述】:

我有一个如下所示的 XML:

<?xml version="1.0"?>
<root>
  <flight>
    <number>10001</number>
    <airport>LAX</airport>
    <dest>
      <airport>SFO</airport>
    </dest>
  </flight>
  <flight>
    <number>10002</number>
    <airport>LAX</airport>
    <dest>
      <airport>JFK</airport>
    </dest>
  </flight>
  <flight>
    <number>10003</number>
    <airport>JFK</airport>
    <dest>
      <airport>LAX</airport>
    </dest>
  </flight>
</root>

使用 XQuery 我需要得到这样的东西:

<res>
    <airport code="LAX">
        <deps>2</deps>
        <dests>1</deps>
    </airport>
    <airport code="JFK">
        <deps>1</deps>
        <dests>1</deps>
    </airport>
    <airport code="SFO">
        <deps>0</deps>
        <dests>1</deps>
    </airport>
</res>

我做到了,并且可以得到正确的结果,但是,我的查询只能找到depsdests,但不能同时找到。

这是我解决问题的方法。

let $all := doc("flights.xml")/root
for $airports in distinct-values($all/flight//*/airport) (:here I get all airport codes:)
order by $airports 

for $nr-dep in $all/flight/airport

where $nr-dep = $airports 
group by $airports 

return <res>
          <airport name="{$airports}"><deps>{count($nr-dep)}</deps></airport>
       </res>

我在这里得到出发次数。我可以通过将for $nr-dep in $all/flight/airport 替换为for $nr-dep in $all/flight/dest/airport 来轻松获得目标,但是我找不到像预期的XML 那样以相同结果显示两者的方法。

【问题讨论】:

    标签: xml xquery basex


    【解决方案1】:

    这是一个使用group by的版本:

    <res>{
        for $airport in //airport
        group by $code := $airport/text()
        order by $code
        return <airport code="{$code}">
            <deps>{ count($airport/parent::flight) }</deps>
            <dests>{ count($airport/parent::dest) }</dests>
        </airport>
    }</res>
    

    【讨论】:

    • 我想明确分组后的排序顺序将是一件好事。通过阅读规范,我认为group by 不能保证一定的顺序。
    • 好点,我在原始查询中忽略了这一点。我会更新我的答案。
    • 我认为这比我的解决方案更优雅。
    【解决方案2】:

    为什么不简单:

    for $airport in distinct-values($all//airport)
    order by $airport
    return <airport code="{$airport}">
      <deps>{count($all//flight/airport[. = $airport])}</deps>
      <dests>{count($all//dest/airport[. = $airport])}</dests>
    </airport>
    

    【讨论】:

    • 它可以工作,但是,我仍然开始使用 XQuery,无法理解这背后的所有细节以及它的工作原理。我不明白//[. = $airport]。非常感谢。
    • // 导致递归树搜索,即“所有后代,不仅是孩子”。它是descendant-or-self::node() 的简写,它是XPath,而不是XQuery。 [. = $value]也是XPath,意思是“如果这个节点的文本值为$value。看来您需要先阅读 XPath。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多