我在此条款中的目标是列出居住在San Fran但在硅谷工作的员工。现在我的条款正在努力找出哪些员工住在San Fran,但我不知道如何加入EmployeeList和WorkInfo这两个名单,以便带走居住在San Fran的员工,并找出这些名字中的哪一个也是在硅谷工作。
这是我到目前为止在我的条款中所拥有的:
for $x in /EmpDatabase/PersonList/Contents/Person
where $x/City='San Fran'
order by $x/Name
return $x/Name
这是我的XML数据文件:
<EmpDatabase>
<PersonList Type="Employee">
<Title Value="Employee List"/>
<Contents>
<Person>
<Name>Susan L. Anderson</Name>
<City>San Fran</City>
<Gender>F</Gender>
</Person>
<Person>
<Name>Dan L. Brady</Name>
<City>Sacramento</City>
<Gender>M</Gender>
</Person>
<Person>
<Name>Peter K. Chen</Name>
<City>San Fran</City>
<Gender>M</Gender>
</Person>
</Contents>
</PersonList>
<CompanyList Type="Company">
<Title Value="Company List"/>
<Contents>
<Company>
<Name>Google</Name>
<City>Silicon Valley</City>
</Company>
<Company>
<Name>Riot</Name>
<City>LA</City>
</Company>
</Contents>
</CompanyList>
<InfoList Type="Works">
<Title Value="Works List"/>
<Contents>
<Works>
<Name>Susan L. Anderson</Name>
<Company>Google</Company>
<Salary>48000</Salary>
</Works>
<Works>
<Name>Dan L. Brady</Name>
<Company>Google</Company>
<Salary>42000</Salary>
</Works>
<Works>
<Name>Peter K. Chen</Name>
<Company>Riot</Company>
<Salary>53000</Salary>
</Works>
</Contents>
</InfoList>
</EmpDatabase>
自然加入正确的方式来解决这个问题吗?如何用XQuery编写自然连接?我是否需要在不同的文件中写一个单独的条款来列出在硅谷工作的员工,然后以某种方式加入这两个条款的结果?
非常感谢任何帮助!
答案 0 :(得分:3)
我将$x
重命名为$person
,以便为其提供更有意义的名称。
您可以制定隐式联接,但更容易制定您实际需要的内容:
for $person in /EmpDatabase/PersonList/Contents/Person
(: retrieve company $person is working for :)
let $works := /EmpDatabase/InfoList/Contents/Works[Name=$person/Name]
where $person/City='San Fran'
(: See if the company has a department in Silicon Valley :)
where /EmpDatabase/CompanyList/Contents/Company[Name=$works/Company and City='Silicon Valley']
order by $person/Name
return $person/Name
如果您更喜欢“经典”联接,只需使用多个for
循环:
for $person in /EmpDatabase/PersonList/Contents/Person
for $works in /EmpDatabase/InfoList/Contents/Works
for $company in /EmpDatabase/CompanyList/Contents/Company
where $person/City='San Fran'
where $person/Name=$works/Name
where $works/Company=$company/Name
where $company/City='Silicon Valley'
order by $person/Name
return $person/Name