跳轉到內容

XQuery/搜尋多個集合

來自華夏公益教科書,開放的書籍,開放的世界

您想在多個集合中查詢記錄。

有幾種方法可以做到這一點。最簡單的方法是將這兩個集合放在一個父集合中,然後從父集合開始搜尋。

假設您有三個集合

  /db/test
  /db/test/a
  /db/test/b

要獲取集合 a 和 b 中的所有書籍,只需指定父集合,即 /db/test

  for $book in collection('/db/test')//book

請注意,雙斜槓 **//** 將在基本集合或任何子集合中的任何位置查詢書籍。

如果您有兩個位於檔案系統中不同位置的集合,您可以簡單地指定每個集合,並使用序列連線操作將它們連線在一起。這是將兩個序列括在括號中的預設操作。例如,如果您有兩個序列 **a** 和 **b**,這兩個序列的連線就是 **(a,b)**。

假設您有兩個集合,在以下集合中包含書籍

File='/db/test/a/books.xml'

<books>
    <book id="47">
        <title>Moby Dick</title>
        <author>Herman Melville</author>
        <published-date>1851-01-01</published-date>
        <price>$19.95</price>
        <review>The adventures of the wandering sailor in pursuit of a 
            ferocious wale.</review>
    </book>
    <book id="48">
        <title>The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>
        <published-date>1925-05-10</published-date>
        <price>$29.95</price>
        <review>Chronicles of an era during the roaring 1920s
                when the US economy soared.</review>
    </book>
</books>

File='/db/test/b/books.xml'

<books>
    <book id="49">
        <title>Catch-22</title>
        <author>Joseph Heller</author>
        <published-date>1961-01-01</published-date>
        <price>$19.95</price>
        <review>A satirical, historical novel set during the later stages of World War II from 1943 onwards.</review>
    </book>
    <book id="48">
        <title>Lolita</title>
        <author>Vladimir Nabokov</author>
        <published-date>1955-01-01</published-date>
        <price>$19.95</price>
        <review>A man becomes obsessed with a 12-year-old girl.</review>
    </book>
</books>

以下查詢將對這兩個集合進行操作。

xquery version "1.0";

let $col-a := '/db/test/a'
let $col-b := '/db/test/b'
return
<books>{
for $book in (collection($col-a)//book, collection($col-b)//book)
return
  $book
}</books>

如果您只想返回標題,可以使用以下內容

xquery version "1.0";

let $col-a := '/db/test/a'
let $col-b := '/db/test/b'
return
<books>{
for $book in (collection($col-a)//book, collection($col-b)//book)
return
  $book/title
}</books>

這將返回以下結果

<books>
<title>Moby Dick</title>
<title>The Great Gatsby</title>
<title>Catch-22</title>
<title>Lolita</title>
</books>
華夏公益教科書