向查询添加更多过滤器

时间:2016-05-19 19:54:42

标签: sql

我有以下查询可行,但现在我被卡住了。我想再添加两个过滤器,我不太清楚如何做到这一点。在表关系中,我有一个称为关系的字段。我需要确保返回的父数据在该字段中具有父亲或继父。同样地,我需要母亲数据由Stepmother,母亲过滤。当然,学生可能没有父亲或母亲,但如果他们有一个父母,我仍然希望返回数据。

WHERE p.pk_PupilID IN('" & pks & "') AND rmother.Relationship IN('Mother','Stepmother') OR rfather.Relationship IN('Father','Stepfather')

到目前为止的代码工作

SELECT DISTINCT  p.pk_PupilID, pn.Title, pn.Forename, pn.Surname, pn.PreferredForename, father.pk_PersonID, father.Title, father.Forename, father.Surname,  mother.pk_PersonID, mother.Title, mother.Forename, mother.Surname, pn.DoB, pn.Gender, h.House, p.Form, p.BoardingStatus, p.Tutor, h.Housemaster , f.Salutation
FROM Family AS f 
LEFT JOIN RELATION AS rpupil ON f.pk_FamilyID = rpupil.fk_FamilyID
LEFT JOIN PUPIL AS p ON rpupil.fk_PersonID = p.pk_PupilID 
LEFT JOIN PERSON AS pn ON p.pk_PupilID = pn.pk_PersonID 
LEFT JOIN HOUSE AS h ON p.fk_DepartmentID = h.fk_DepartmentID 
LEFT JOIN RELATION AS rfather ON p.pk_PupilID = rfather.fk_PersonID 
LEFT JOIN PERSON AS father ON rfather.fk_RelatedPersonID = father.pk_PersonID 
LEFT JOIN RELATION AS rmother ON p.pk_PupilID = rmother.fk_PersonID 
LEFT JOIN PERSON AS mother ON rmother.fk_RelatedPersonID = mother.pk_PersonID 
WHERE p.pk_PupilID IN('" & pks & "') 

2 个答案:

答案 0 :(得分:1)

此处有格式化评论。

有关OR ...

的注意事项

此:

WHERE p.pk_PupilID IN('" & pks & "') 
AND rmother.Relationship IN('Mother','Stepmother') 
OR rfather.Relationship IN('Father','Stepfather')

像这样处理:

WHERE (
     p.pk_PupilID IN('" & pks & "') 
AND  rmother.Relationship IN('Mother','Stepmother')
      )
OR   rfather.Relationship IN('Father','Stepfather')

您需要使用括号()来定义您希望WHERE应用于的OR子句的部分:

WHERE p.pk_PupilID IN('" & pks & "') 
AND (
     rmother.Relationship IN('Mother','Stepmother') 
OR   rfather.Relationship IN('Father','Stepfather')
    )

这样,您的OR子句选项也必须满足WHERE p.pk_PupilID IN('" & pks & "')

无论如何,我没有足够的信息知道这是否能真正解决您的问题。一些示例数据会有所帮助,因此我们可以知道不应该返回什么,或者不应该返回什么。

答案 1 :(得分:-1)

如果你确定将填充四个“父”值中的一个,你可以使用它:

where(p.pk_PupilID IN('" & pks & "') AND rmother.Relationship IN('Mother','Stepmother')) or (p.pk_PupilID in('" & pks & "') AND rfather.Relationship IN('Father','Stepfather'))