【】Er 1.0: An XML Query Language 2004-7-23 Section 3 Section 8 - Section 10

xiaoxiao2021-03-06  78

3.8 FLWOR Expression FLWOR Expressions

XQuery provides features named FLWOR expression, supports iterations and variables and intermediate results. Such expressions are often useful for calculation and reconstruction data to connect 2 or more documents. Name FLWOR Send "Flower" sound, hint keyword for, let, where, order by, and return.

[28]

FLWOREXPR

:: =

(Forclause | LetcLause WhereClause? OrderByClause? "Return" EXPRSINGLE

[29]

FORCLAUSE

:: =

"for" "$" VARNAME TYPEDECLATION? POSITIONALVAR? "in" exprsingle ("," "$" VarName Typedeclaration? POSITIONALVAR? "in" exprsisingle) *

[31]

LetcLause

:: =

"Let" "$" varName Typedeclaration? ": =" EXPRSIINGLE ("," $ "varName type": = "exprsingle) *

[109]

Typedeclaration

:: =

"AS" Sequencetype

[30]

Positionalvar

:: =

"AT" "$" Varname

[32]

WHERECLASE

:: =

"Where" expr

[33]

ORDERBYCLAUSE

:: =

("ORDER" "by" | "stable" "Order" "by") OrderspeClist

[34]

ORDERSPECLIST

:: =

ORDERSPEC ("," Orderspec) *

[35]

ORDERSPEC

:: =

Exprsingle ORDERMODIFIER

[36]

OrderModifier

:: =

("Ascending" | "descending")? ("Empty" "" "" "" "" "" "StringlItemal)?

The FOR and LET clauses in the FLWOR expression generate a group of tuples that bind variables, called tetrans (TUPLE STREAM). Optional WHERE clauses are used to filter elements, retain certain tuples and delete others. Optional clauses Order BY can be used to record tetanflows. RetURN clause construct the result of the FLWOR expression. After the RETURN clause is filtered in the WHERE clause, the RETURE clause is filtered, and the variable bound in the corresponding tuple is calculated once in each tuple stream. The result of the FLWOR expression is an ordered sequence that contains these calculated connection results.

Below is an example of a FLWOR expression that contains all possible clauses. The FOR clause is iterated for all departments in the input document, and the variable is binded to each department number. For each $ d, the Let clause will be bound to all the employees (Employees) selected from the other input document. The result of the FOR clause and the LET clause is a meta stream, where each tuple contains a pair of $ D and $ E binding ($ D is bound to department numbers, $ E and a group of employees in that department tied set). The WHERE clause filter element stream, retains the binding pairs of at least ten employees that represent the department. The Order By clause continues in order to sort the descending sequence of employees in the department. Return clauses construct a new element BIG-DEPT containing a new element number number, the total number of staff is salary. For $ d in Fn: DOC ("depts.xml") // deptno

Let $ E: = FN: DOC ("Emps.xml") // EMP [deptno = $ d]

WHERE FN: Count> = 10

ORDER BY FN: AVG ($ E / SALARY) Descending

Return

{

$ D,

{fn: count ($ e)} ,

{fn: AVG ($ E / SALARY)}

}

There are more descriptions of clauses in the Flowor expression.

3.8.1 for and let clause for and let clauses

The purpose of the FOR and LET clauses in the FLWOR expression is to generate a metapult stream, where each tuple contains one to more binding variables.

An example of the simplest FOR clause contains a variable and an associated expression. We call the value of the expression as an input sequence. The FOR clause iterates the data item in the sequence, and the variable is bound to each data item. If the sort mode is ORDERED, the result sequence of the variable binding is sorted in order of the value of the input sequence; otherwise, the order of variable binding is the implementation-dependent.

A FOR clause may also contain multiple variables, each variable has an associated expression whose value is the input sequence of that variable (INPUT Sequence). In this case, the FOR clause iterates each variable to its input sequence. The resulting component stream contains a group of groups to each value of the Cartesian product of each value and the input sequence. If the ordering mode is ORDERED, the order of the metaded stream is mainly determined by the order of the input sequence of the leftmost variable, and then determines from the left to right by other variables. Otherwise, the order of the variable bindings is implemented (IMPLEMENTATION-Dependent).

A Let clause may also contain one or more variables, each variable has an associated expression. However, different from the For clause is that a LET clause binds each variable with its associated expression, and does not iterate. The variable binding generated by the Let clause is added to the binding tuple generated by the For clause. If there is no For clause, the Let clause generates a tuple that contains all variables.

Although the FOR clause and the LET clause is bound to the variable, the modulus binding method is completely different, the same as the following example. The first example used a Let clause:

Let $ s: = (, , ) Return {$ s}

Variable $ S is bound to the results of the expression (, , ). Since there is no For clause, the Let clarifier generates a tuple containing a binding of $ s. ReturN clause calls this tuple, create the following output:

The next example is a simple query that contains a FOR clause instead of a Let clause:

For $ s in (, , )

Return {$ S}

In this example, the variable $ S iterate gives a given expression. If the sort mode is ORDERED, $ S first and bound, then and , final and bind. These bindings each generate a tuple, and the return clause calls each tuple, creating the following output:

The following example shows how the binding Mode is generated by a FOR clause containing multiple variables when the sort mode is ORDERED.

For $ I in (1, 2), $ J in (3, 4)

The packets generated by the above For clauses are as follows:

($ i = 1, $ j = 3)

($ I = 1, $ j = 4)

($ I = 2, $ j = 3)

($ i = 2, $ j = 4)

If the sort mode is unordered, the FOR clause in the previous example will generate the same tuple stream, but the tuple order will be the implementation-dependent.

The scope of the variable binding in the For clause or the LET clause, including all sub-expressions after the variable binding in the FLWOR expression. The scope does not include the expression bound by the variable. The following example shows how the FOR and LET clause will reference the variables bound in the earlier clause in the same FLWOR expression:

For $ x in $ w

Let $ Y: = f ($ x)

For $ z in g ($ x, $ y)

Return H ($ x, $ y, $ z)

The variables bound in each for or the LET clause will have an optional type declaration, which is a type of grammar declaration in 2.4.3 SequenceType Syntax. According to the sequence type matching rule, if the type of the value of the variable is not matched with the type of the declaration, a type error will be triggered. [Err: XP0004] [Err: XP0006] For example, the following expression triggers a type error (Type error) because the variable $ SALARY has a type declaration that is not satisfied with the value binding with the variable:

Let $ SALARY AS: DECIMAL: = "CAT"

Return $ SALARY * 2FOR clauses Bind each variable will be bound to a Positional Variable. The name of the name of the position variable is the keyword AT. The location variable always has a hidden type xs: integer. When a variable iterates the data item in the sequence, its position variable iterative input sequence represents an integer of the position of the data item sequence, starting from 1.

The following For clause describes the position variable:

For $ car at $ i in ("ford", "chevy"),

$ PET AT $ J in ("Cat", "DOG")

If the ordering mode is Ordered, the packet generated by the above For clause is as follows:

($ I = 1, $ car = "ford", $ j = 1, $ pET = "cat")

($ I = 1, $ car = "ford", $ j = 2, $ pET = "DOG")

($ i = 2, $ car = "chevy", $ j = 1, $ pET = "cat")

($ I = 2, $ car = "chevy", $ j = 2, $ pET = "DOG")

If the sort mode is unordered, the resulting element stream contains the same tuple in the order of implementation-dependent.

3.8.2 Where clause Where Clause

An optional WHERE clause makes a filter service for a tetan that is binded by the Variables generated by the For and the LET clause. The expression in the WHERE clause is called where-expression, which is calculated for each tuple. If the valid Boolean value of the WHERE expression is true, the tuple is reserved and its variable bind is used for execution of a retURN clause. If the effective Boolean value of WHERE-Expression is false, the tuple is deleted. The effective boolean value of the expression is defined in 2.3.3 Effective Boolean Value.

The following expression shows how the WHERE clause will be applied to the positional variable to complete a sample of an input sequence. This expression is approximately the average of a sequence by extracting a sample from each of the input values.

FN: AVG (for $ x at $ I in $ INPUTVALUES

Where $ i mod 100 = 0

Return $ x)

3.8.3 ORDER BY and RETURN Sentence Order by And Return Clauses

The RetURN clause of the FLWOR expression is calculated once in each tuple in the tuple stream, which is the result of forming the FLWOR expression.

If there is no ORDER BY clause, the order of the metapatom stream is determined by the for and LET clauses according to the order mode (Ordering mode). If there is a Order By clause, it is sequencing the tuple in a new, value-based order. Regardless of which occurs, the order obtained is determined to determine that the RETURN clause uses the variables in the corresponding tunnel to bind the order each time each tuple calculation. Note If there is an ORDER BY clause exists, the ordering mode is invalid in the FLWOR expression because the ORDER BY priority is higher than the ordering mode. As shown in the above grammar, an ORDER BY clause contains one or more sort specification, called OrdersPecs. For each tuple in the tuple stream, the order used in the tem of groups calculates ORDERSPEC. The order relationship between the two tuples is determined by the value of their ORDERSPEC, and the left to right is compared until a pair of values. If the value of the comparison is a string, ORDERSPEC indicates the copy of the proofer to use (if no school pair is specified, the default proofread is used.)

The process of calculating and comparing ORDERSPEC is based on the following rules:

The result of each ORDERSPEC is atomization. If the result of the atomization is neither a single atom value, it is not an empty sequence, which will trigger a type error [Err: XP0004] [Err: XP0006].

If a value of an ORDERSPEC has a dynamic type xdt: untypedatomic (such as a schema) document), it is assigned to the XS: String type.

note:

It consists of the start of the unmatched value as a string, and the sorting process is started when the complete knowledge of the sorted value type is missing.

All ORDERSPEC types must be the Subty Substitution and / or Type Promotion to convert to public types. Sort by the minimum common type of operator GT. If the two or more ORDERSPEC values ​​are not converted to the public type of operator GT, a type error will be triggered [Err: XP0004] [Err: XP0006].

Example: The ORDERSPEC value contains a value of the hazize type from XS: Integer, and a value of the shoesize type from XS: Decimal. The minimum public type value that is obtained by sub-type replacement and numerical types is XS: Decimal.

Example: The ORDERSPEC value contains a value of an XS: string type and a value of an XS: anyuri type. Since these types cannot get a common type through sub-type substitution and numerical types, a type error is triggered.

When comparing two ORDERSPEC values ​​to determine their relative positions in the sort sequence, greater than the (Greater-Than) is defined as follows:

When ORDERSPEC specifies Empty Least, if one of the following conditions is true, the value W is considered to be greater than the value V:

V is a space sequence and W is a non-empty sequence.

V is nan, and W is neither nan nor is not a null sequence.

The school pair is not specified, and W GT V is true.

The specific school pair C is specified, and Fn: Compare (V, W, C) is less than zero.

When ORDERSPEC specifies Empty GreateSt, if one of the following conditions is true, the value W is considered to be greater-Than value V: W is a space sequence, and V is a non-empty sequence.

W is nan, and V is neither nan nor is not a space sequence.

The school pair is not specified, and W GT V is true.

The specific school pair C is specified, and Fn: Compare (V, W, C) is less than zero.

When the ORDERSPEC has neither EMPTY Least does not determine EMPTY GREATEST, it is an implementation-defined.

If T1 and T2 are two tuples in the tuple stream, and V1, V2 is when the orderspec is calculated from left to right, the first to a value greater-Than (such as The above definition), then:

If V1 is greater than (Greater-Than) V2: If the ORDERSPEC specifies the descending, the position of T1 is placed in T2 at the position in the tuple stream; otherwise, the position of T2 is before T1 in the tetan stream.

If V2 is greater than (Greater-Than) V1: If the ORDERSPEC specifies the descending (Descending), T2 is placed before T1 in the tetan stream; otherwise, the position of T1 in t2 in T2 in t2.

If any pair of OrderSpeCs, V1 and V2 for tuples T1 and T2 are not greater than (Greater-Than) one, then:

If Stable is specified, the original order of T1 and T2 is maintained in the meta stream.

If Stable is not specified, the order of T1 and T2 in the packet stream is an implementation-dependent.

The ORDER BY clause makes it easy to classify the results of a FLWOR expression, even if the classification keyword is not included in the expression results. For example, the following expression returns an employee name according to salary, does not return a specific salary:

For $ E IN $ EMPLOYEES

Order by $ E / SALARY DESCENDING

Return $ E / NAME

The ORDER BY clause is the functionality of XQuery provided in addition to the only specified order other than document order (Document Order). Therefore, even if it is not required, each query except that the order is required to be sorted, and a query must contain a Flowor expression. For example, a list of books with less than 100 can be simpler than a path expression such as $ BOOKS / / BOOK [Price <100]. But if these books returns in the order of the book name, the query must be represented as follows:

For $ b in $ BOOKS / / BOOK [price <100]

Order by $ b / TITLE

Return $ B

The following example illustrates an ORDER BY clause that uses several options. It makes a collection of books to be sorted by book name, followed by price descending order. A specific proofread is sorted by the book name, and in price sorts, there is no price book that does not have price (just like they have a minimum price). As long as the two books with the same book name and price, the keyword indicates that their input order will be retained.

For $ b in $ books // book

Stable Order by $ B / TITLE COLLATION "ENG-US", $ B / Price Descending EMPTY Least

Return $ B

3.8.4 Example Example

The following example shows how the FLWOR expression is nested, and how to specify the order relationship at the multi-level element level. The sample query reverses the hierarchy of a document to transform a book catalog into a list of author. Entering the book is a list of books, each of which contains a list of authors. The example is based on the following:

TCP / IP Illustrated </ Title></p> <p><Author> Stevens </ Author></p> <p><Publisher> Addison-Wesley </ Publisher></p> <p></ book></p> <p><book></p> <p><title> advanced programming</p> <p>In The Unix Environment </ Title></p> <p><Author> Stevens </ Author></p> <p><Publisher> Addison-Wesley </ Publisher></p> <p></ book></p> <p><book></p> <p><title> Data on the Web </ Title></p> <p><author> Abiteboul </ author></p> <p><author> bundan </ author></p> <p><Author> SUCIU </ Author></p> <p></ book></p> <p></ bib></p> <p>The following query will enter the text into a list, where each author's name only occurs once, followed by the author's book name. Function fn: DistINCT-VALUES is used to remove duplicate (value) from the list list. Author's list and bookmaps published by each author use the default proofread, returning in alphabetical order.</p> <p><authlist></p> <p>{</p> <p>For $ a in Fn: Distinct-Values ​​($ BOOKS // Author)</p> <p>Order by $ a</p> <p>Return</p> <p><author></p> <p><name> {$ a} </ name></p> <p><books></p> <p>{</p> <p>For $ b in $ books // book [author = $ a]</p> <p>Order by $ b / TITLE</p> <p>Return $ B / TITLE</p> <p>}</p> <p></ books></p> <p></ author></p> <p>}</p> <p></ authlist></p> <p>The results of the above expressions are as follows:</p> <p><authlist></p> <p><author></p> <p><name> Abiteboul </ name></p> <p><books></p> <p><title> Data on the Web </ Title></p> <p></ books></p> <p></ author></p> <p><author></p> <p><name> bundan </ name></p> <p><books></p> <p><title> Data on the Web </ Title></p> <p></ books></p> <p></ author></p> <p><author></p> <p><name> Stevens </ name></p> <p><books></p> <p><Title> TCP / IP Illustrated </ Title></p> <p><title> advanced programming</p> <p>In The Unix Environment </ Title> </ books></p> <p></ author></p> <p><author></p> <p><name> SUCIU </ Name></p> <p><books></p> <p><title> Data on the Web </ Title></p> <p></ books></p> <p></ author></p> <p></ authlist></p> <p>3.9 Ordered and Distributed Expression Ordered and Unordered Expressions</p> <p>[81]</p> <p>OrderedExpr</p> <p>:: =</p> <p>"ORDERED" "{" expr "}"</p> <p>[82]</p> <p>UnorderedExpr</p> <p>:: =</p> <p>"unordered" "{" expr "}"</p> <p>Ordered and unordered expressions are to set the ordering mode in the static context (Ordered) or unordered or unordered or unordered or unordered ). The specified sort mode is applied to an expression nested in the curly brackets. For expressions that are sorted by their results, the sort mode can be set to unordered to implement an excellent performance, so that the authorization system flexibly returns the result in the most efficient order.</p> <p>Sort Mode (Ordering Mode) affects path expression, Union, INTERSECT, and Except expressions, and the operating mode of FLWOR expressions without Order By clauses. If the sort mode is ordered, the node sequence returned by the path, UNION, INTERSECT, and Except expressions is document order (otherwise the order of these return sequences is implemented). Sort mode The role of the FLWOR expression is described in 3.8 FlWor Expresss. Sort mode has no effect on repeated deletion.</p> <p>note::</p> <p>In a query area of ​​a sort mode for unordered, some of the functionality that relies on node order returns an unsure result. These functions include FN: Position, Fn: Last, Fn: Index-of, Fn: Insert-Before, Fn: Remove, Fn: Reverse, and Fn: Subsequence. In a disorderless area, the numerical predicate in a path expression is also uncertain. For example, in a ordered area, path expression // A / b [5] will return the fifth defined B element in the document order (Document ORDER). In a disorder area, the same expression will return a B-Element defined by implementation-dependent.</p> <p>The use of unordered expressions is described in the following example, this example will join two documents named Parts.xml and Suppliers.xml. Example Returns the number of red parts and supplies suppliers of these parts. If there is no unordered expression, the result (part number, supplier number) has a sequence of the list, which is mainly controlled by the document order of Parts.xml, followed by Suppliers. XML's Document Order Control. However, if the sort of the results is not important, this may not be the most effective way to process the query. A xQuery implementation can use the index to find a red part, or use the main order of the Suppliers.xml control results instead of Parts.xml to make a more efficient processing query. The unordered expression gives the query evaluation program to use this optimized freedom. Unordered {</p> <p>For $ p in fn: DOC ("parts.xml") // part [color = "red"],</p> <p>$ s in fn: DOC ("suppliers.xml") // support</p> <p>Where $ p / supportno = $ s / support</p> <p>Return</p> <p><ps></p> <p>{$ P / Partno, $ S / Suppn}</p> <p></ ps></p> <p>}</p> <p>In addition to the Ordered expression and unordered expression, XQuery provides a function called FN: unordered, which acts on any of the sequence of data items and returns the same sequence in an uncertain order. The call to the fn: unordered function is considered to be implemented in any system to be considered by any system. FN: unordered function is different from the unordered expression:</p> <p>Function fn: unordered only for its sequence sorting of operation objects, and the unordered expression sets a sort mode for its operation object expression and all of its nested expressions.</p> <p>Function fn: unordered can work for any sequence, and the unordered expression only affects the order of the node sequence (not a sequence of atom).</p> <p>3.10 Conditions Expression Conditional Expressions</p> <p>XQuery supports keyword IF, THEN, and ELSE conditional expressions.</p> <p>[40]</p> <p>IFEXPR</p> <p>:: =</p> <p>"if" ("expr" "" "" exprsingle "else" exprsingle</p> <p>The expression followed by the keyword IF called test expression (Test Expression), followed by the expression after the keyword THEN and ELS, called THEN Expression (ELSE-Expression) and SELE-Expression .</p> <p>Processing a conditional expression is a first step in finding a valid boolean value of test expressions, as defined in 2.3.3 Effective Boolean Value.</p> <p>The value of a conditional expression is as follows: If the valid Boolean value of the test expression is TRUE, the value of the THEN expression is returned. If the effective Boolean value of the test expression is false, the value of the ELSE expression is returned.</p> <p>The conditional expression has a special rule for communication dynamic errors. If the valid value of the test expression is true, the conditional expression ignores (not trigger) any dynamic errors encountered in any else expression. In this case, since the ELSE expression is not worth noting, it does not need to be evaluated. Similarly, if the valid value of the test expression is false, the conditional expression ignores any dynamic error (Dynamic Errors) encountered in the THEN expression, and the THEN expressions do not need to be evaluated. Here are some examples of conditions of expression:</p> <p>In this case, the test expression is a comparative expression:</p> <p>· IF ($ Widget1 / Unit-Cost <$ widget2 / unit-cost)</p> <p>· THEN $ Widget1</p> <p>· ELSE $ widget2</p> <p>In this example, the test expression test attribute name discounted existence, does not depend on and attribute values:</p> <p>· IF ($ part / @ discounted)</p> <p>· THEN $ Part / Wholesale</p> <p>· ELSE $ part / retail</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-105336.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="105336" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.061</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'ByooESQYbqH7h7WDioCMD23bHijldBndrtTCxnOqry0R16z9Lz99NpsPuTCqWG5DoMw1EZIeg95qZ3mSMLabiw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>