[英]Is it possible to use OR on a where clause in XQuery?
我需要返回作者為“ John Doe”的書籍和期刊的標題,但是我的xml文件設置為:
<library>
<book>...</book>
<article>...</article>
</library>
共有6本書和期刊。
我知道,如果這是SQL,則可以執行以下操作:
SELECT title
FROM library
WHERE bookauthor = "John Doe" OR articleauthor = "John Doe"
( 該數據庫不會被規范化,但是我試圖證明我知道我需要做什么,只是不確定如何使用XQuery )
我嘗試了以下操作,它返回了所有6個標題:
for $x in doc("xmldata.xml")/library
let $a := $x/article
let $b := $x/book
return ($a/title, $b/title)
但是我不確定該處理where子句。 同樣,我嘗試了以下操作並陷入同一點:
for $x in doc("xmldata.xml")/library
return ($x/article/title, $x/book/title)
當我嘗試添加where子句時,即使它只返回一本書和一則文章,它仍會返回所有6個條目:
for $x in doc("xmldata.xml")/library
where $x/article/author = 'John Doe'
where $x/book/author = 'John Doe'
return ($x/article/title, $x/book/title)
有人能幫我嗎? 也許是通過向我指出正確的方向或指出我要去哪里錯。
完整的XML文件:
<library>
<book>
<author>John Doe</author>
<title>Turnitin</title>
</book>
<article>
<author>John Doe</author>
<title>Evaluating</title>
</article>
<article>
<author>Shannon, L.</author>
<title>Reconceptualising</title>
</article>
<book>
<author>Burden, David</author>
<title>An evaluation</title>
</book>
<article>
<author>Moscrop, C.</author>
<title>Evaluating a systematic method</title>
</article>
<book>
<author>Beaumont, C.</author>
<title>Beyond e-learning</title>
</book>
</library>
抱歉,我錯過了您要查詢的路徑。 庫元素只有一個,因此您的for
循環僅重復一次,然后由於至少有一個 <author>
與where
子句匹配,因此它返回了<library>
所有值。
解決方案是在層次結構中向下迭代一級:
for $x in doc("xmldata.xml")/library/*
where $x/author = 'John Doe'
return $x/title
或者,如果您想非常清楚地選擇哪些元素:
for $x in doc("xmldata.xml")/library/(article|book)
...
要控制不同元素的值輸出,可以在返回中使用不同的XPath:
...
return ($x/self::book/title, $x/self::article/author)
您可以使用通配符*
來匹配元素,而不考慮其名稱:
doc("xmldata.xml")/library/*[author = 'John Doe']/title
這相當於更冗長的FLWOR表達式
for $entry in doc("xmldata.xml")/library/*
where $entry/author = 'John Doe'
return $entry/title
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.