帮助编写德比的数据库查询?

时间:2010-03-12 02:30:43

标签: derby

我有一个包含多个表(人物,父母等)的数据库

人员表具有某些属性,特别是ssn,countryofbirth和currentcountry。

父母表有ssn和fathersbirthcountry

ssn in Person与父母中的ssn相同 - 这就是他们的联系方式。

我正在努力输出所有与他们的父亲生育国家相同的国家分娩的人的SSN,并且他们也拥有与父亲生育国家相同的当前国家。

SELECT Person.ssn 
FROM Person, Parents 
WHERE fathersbirthcountry = countryofbirth 
AND currentcountry = fathersbirthcountry;

以上似乎没有用,有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

您无法明确将个人记录与父记录链接的条件。对于这个例子,我假设Person包含一个额外的字段,你没有提到,叫做FatherSSN。如果是这样的话:

   SELECT Person.SSN 
   FROM Person, Parents
   WHERE Person.FatherSSN = Parents.SSN
     AND Person.CountryOfBirth = Parents.FathersBirthCountry
     AND Person.CurrentCountry = Parents.FathersBirthCountry

或者,在SQL-92 JOIN语法中:

   SELECT Person.SSN 
   FROM Person INNER JOIN Parents
   ON Person.FatherSSN = Parents.SSN
     AND Person.CountryOfBirth = Parents.FathersBirthCountry
     AND Person.CurrentCountry = Parents.FathersBirthCountry

这两个版本应该产生相同的结果(和执行计划)。

最后,如果这是您自己的数据库,它可以轻松且有利地重构,只包含一个Person表,其中包含所有代,使用与您现在使用的完全相同的结构。如果进行重组,您的SQL将如下所示:

   SELECT P1.SSN 
   FROM Person P1 INNER JOIN Parents P2
   ON P1.FatherSSN = P2.SSN
     AND P1.CountryOfBirth = P2.CountryOfBirth
     AND P1.CurrentCountry = P2.CountryOfBirth

答案 1 :(得分:0)

你永远不会提到人们如何存储其对父母的引用。我假设在Person表中有一个MotherId和FatherId,所以你会得到:

Select SSN
From Person
Where BirthCountry =    (
                        Select BirthCountry
                        From Parents
                        Where Person.FatherId = Parents.Id
                        )

现在,假设Person表中的BirthCountry与Parents表中的BirthCountry相同。

相关问题