SQL连接四个表中的数据,其中有多个

时间:2015-02-25 10:24:44

标签: sql

您好我有以下sql语句,用于精细链接四个表。表格是Person(c,e),Relation(d),PersonFamily(b),Family(a)。 我添加条件WHERE d.Relationship LIKE'%Father'因为我想过滤那个特定的关系所以它只检索(c)的数据,如果这个关系是父亲,继父,祖父等等。一旦我添加了这个,它失败 - 我没有设法找到具有多个条件的示例,因为我需要为母亲添加另一个条件,但我希望它出现在f.Title,f.Forename,f.Surname下的同一行中。

我想如果我能理解如何在sql中执行多重操作,我可能也可以检索出母数据

SELECT a.pk_FamilyID, a.Salutation, e.Title, e.Forename, e.Surname, c.Title, c.Forename, c.Surname
FROM Family a
INNER JOIN PersonFamily b ON a.pk_FamilyID = b.fk_FamilyID
INNER JOIN Person c ON b.fk_PersonID = c.pk_PersonID
INNER JOIN Relation d ON c.pk_PersonID = d.fk_RelatedPersonID
WHERE d.Relationship LIKE '%Father'
INNER JOIN Person e ON d.fk_PersonID = e.pk_PersonID
WHERE e.pk_PersonID IN('" & Substitute ( ListOfPersonUUID ; ¶ ; "','" ) & "')
ORDER BY e.SurnameForename ASC

2 个答案:

答案 0 :(得分:0)

您可以在使用AND/OR运算符的位置添加多个条件,以满足您的要求。在这种情况下,您可能需要使用AND运算符。我假设您希望获得结果,如果%Father OR %Mother中存在关系,那么为什么在部分中添加(d.Relationship LIKE '%Father' OR d.Relationship LIKE '%Mother')条件。

SELECT a.pk_FamilyID, a.Salutation, e.Title, e.Forename, e.Surname, c.Title, c.Forename, c.Surname
FROM Family a
INNER JOIN PersonFamily b ON a.pk_FamilyID = b.fk_FamilyID
INNER JOIN Person c ON b.fk_PersonID = c.pk_PersonID
INNER JOIN Relation d ON c.pk_PersonID = d.fk_RelatedPersonID
INNER JOIN Person e ON d.fk_PersonID = e.pk_PersonID
WHERE (d.Relationship LIKE '%Father' OR d.Relationship LIKE '%Mother')
AND e.pk_PersonID IN('" & Substitute ( ListOfPersonUUID ; ¶ ; "','" ) & "')
ORDER BY e.SurnameForename ASC

答案 1 :(得分:0)

您不能在同一数据集上拥有多个WHERE子句。条件需要由ANDOR之类的逻辑运算符分隔,或者您需要将WHERE放在数据集中。

你可以拥有:

SELECT a.pk_FamilyID, a.Salutation, e.Title, e.Forename, e.Surname, c.Title, c.Forename, c.Surname
FROM Family a
INNER JOIN PersonFamily b ON a.pk_FamilyID = b.fk_FamilyID
INNER JOIN Person c ON b.fk_PersonID = c.pk_PersonID
INNER JOIN (SELECT * FROM Relation d WHERE Relationship LIKE '%Father')ON c.pk_PersonID = d.fk_RelatedPersonID
INNER JOIN (SELECT * FROM Person WHERE pk_PersonID IN('" & Substitute ( ListOfPersonUUID ; ¶ ; "','" ) & "'))e ON d.fk_PersonID = e.pk_PersonID
ORDER BY e.SurnameForename