我有一个查询,查找符合给定条件的学生记录(相同的ClassNum和匹配的名称或匹配的电子邮件)。任何状态为“已删除”的学生都应该被忽略。
以下查询找到正确的重复项并忽略“学生”中已删除的学生,但我找不到一种方法来阻止它与'dup'中的已删除学生匹配。
案例1:有两个“John Smith”在同一个班级注册。该查询将返回2行,每个John Smith找到一行。这是正确的行为。
案例2:有两个“John Smith”在同一个班级注册,但其中一个的状态为“已删除”。该查询返回未删除的John Smith的一行。这不是我想要的。
我尝试将两个WHERE子句放在ON部分中,将ON和WHERE之间的子句分开等,但都给出了相同的结果。
SELECT DISTINCT Students.Id,
Students.ClassNum,
Students.Lastname,
Students.Firstname,
Students.Status,
Students.Email
FROM Students
INNER JOIN (
SELECT Id,ClassNum,Email,Lastname,Firstname,Status
FROM Students
) dup
ON ( Students.Id != dup.Id
AND Students.ClassNum = dup.ClassNum
AND ( ( Students.Email = dup.Email
AND Students.Email != ''
)
OR ( Students.Lastname = dup.Lastname
AND Students.Firstname = dup.Firstname)
)
)
WHERE Students.Status != 'Deleted'
AND dup.Status != 'Deleted'
答案 0 :(得分:0)
逻辑 OR 通常表示SQL UNION;所以试试这个:
SELECT Students.Id,
Students.ClassNum,
Students.Lastname,
Students.Firstname,
Students.Status,
Students.Email
FROM Students lhs
JOIN Students rhs
on lhs.ClassNum = rhs.ClassNum
and lhs.Firstname = rhs.Firstname
and lhs.LastName = rhs.LastName
and lhs.Status != 'DELETED'
and rhs.Status != 'DELETED'
UNION
SELECT Students.Id,
Students.ClassNum,
Students.Lastname,
Students.Firstname,
Students.Status,
Students.Email
FROM Students lhs
JOIN Students rhs
on lhs.ClassNum = rhs.ClassNum
and lhs.Email = rhs.Email
and lhs.Status != 'DELETED'
and rhs.Status != 'DELETED'