MySQL查询复合语句未返回预期结果

时间:2017-10-04 23:37:50

标签: mysql sql

我们正在尝试构建一个过滤掉标识为SuspendedInactive的员工的查询(这些值字符串显示在“状态列”的数据表中)。如果员工具有这些状态中的任何一个,则他们会显示在On Hold数据表中,而不是Fail数据表中。

在下面的情景中,'Jane Doe'确实让她Approval失败,但因为她是Inactive,她应该被On Hold处理,而不会出现在Fail中数据表。

当我们运行以下查询时,我们预计这些结果会出现在Fail表中:

Employee ID   FirstName   LastName   Status    Eligibility   Approved
  123456        Jim        James      OK            OK      Not Approved
  777889        Ray        Raymond    OK         Ineligible      OK

但我们看到了:

Employee ID   FirstName   LastName   Status    Eligibility   Approved
  123456        Jim        James      OK            OK      Not Approved
  123412        Jane       Doe        Inactive      OK      Not Approved
  777889        Ray        Raymond    OK        Ineligible       OK

这是我们运行的查询,但Inactive员工继续出现,尽管第一个复合语句(我们在此数据运行中没有任何Suspended员工,如果这有所不同)。< / p>

SELECT 
     emp_id, 
     first_name, 
     last_name, 
     status, 
     eligibility, 
     approved
FROM 
     `pass_fail` 
WHERE(
      status <> 'Inactive' 
OR 
      status <> 'Suspended'
) 
AND (
      eligibility ='Ineligible'
OR 
     approved = 'Not Approved')

2 个答案:

答案 0 :(得分:1)

我会使用innot in。根据您的逻辑,查询将是:

SELECT emp_id, first_name, last_name, status, eligibility, approved
FROM pass_fail
WHERE status NOT IN ('Inactive', 'Suspended');

您的文字未说明应如何使用eligibilityapproved。但我推测:

SELECT emp_id, first_name, last_name, status, eligibility, approved
FROM pass_fail
WHERE status NOT IN ('Inactive', 'Suspended') AND
      (eligibility  = 'Ineligible' OR approved = 'Not Approved');

答案 1 :(得分:0)

将两个状态条件之间的OR更改为AND

SELECT emp_id, first_name, last_name, status, eligibility, approved
FROM `pass_fail` 
WHERE status <> 'Inactive' 
  AND status <> 'Suspended'
  AND (eligibility ='Ineligible' OR approved = 'Not Approved')