5.2 Defining Keys & their ReferencesDefining Keys & their References
ref30In the 1999 quarterly report, the
description of every billed part appears only once. We
could enforce this constraint using unique, however, we also want
to ensure that every part-quantity element listed under a
zip code has a corresponding part description. We enforce
the constraint using the
key and
keyref elements. The report schema, report.xsd, shows that the
key and keyref constructions are
applied using almost the same syntax as unique. The key element
applies to the number attribute value of
part elements that are children of the
parts element. This declaration of
number as a key means that its value must be unique
and cannot be set to nil (i.e. is not nillable), and the
name that is associated with the
key, pNumKey, makes the key referenceable from
elsewhere.
To ensure that the part-quantity elements have
corresponding part descriptions, we say that the
number attribute ( <field>@number</field>
<field xpath="@number"/>) of those
elements
(<selector>zip/part</selector>
<selector xpath="r:regions/r:zip/r:part"/>)
must reference the pNumKey key. This
declaration of number as a keyref does not
mean that its value must be unique, but it does mean there
must exist a pNumKey with the same value.
As you may have figured out by analogy with unique, it is possible to
define combinations of
key and
keyref values. Using this mechanism, we could go
beyond simply requiring the product numbers to be equal,
and define a combination of values that must be equal. Such
values may involve combinations of multiple value types
(string, integer,
date, etc.), provided that the order and type of
the field element
references is the same in both the key and keyref definitions.
|