查询不喜欢返回奇怪的结果

时间:2019-12-12 15:10:54

标签: sql

我很困惑的简单查询。我正在尝试过滤出以4120结尾的工作,依此类推。当我运行此查询

select Job.Job, Job.Status from Job 
    Where(Job.Job Not Like '%4120'
          And Job.Job Not Like '%4235'
          And Job.Job Not Like '%4236'
          And Job.Job Not Like '%5910'
          And Status = 'Active' OR Status = 'Complete') 
    Order By Job.Job

我得到这些结果

    Job         Status
    01-19-4120  Complete
    01-19-4235  Complete
    01-19-5910  Complete
    02-19-4120  Complete
    02-19-4235  Complete
    02-19-4236  Complete
    02-19-5910  Complete
    03-07-4120  Complete
    03-19-4120  Complete
    03-19-4235  Complete
    03-19-5910  Complete
    04-19-4120  Complete
    04-19-4160  Complete

我的查询出问题了吗?

5 个答案:

答案 0 :(得分:2)

您有一个逻辑上的先发问题。我高度怀疑您应该在OR条件下加上括号,如下所示:

Job.Job Not Like '%4120'
And Job.Job Not Like '%4235'
And Job.Job Not Like '%4236'
And Job.Job Not Like '%5910'
And (Status = 'Active' OR Status = 'Complete') 

说明:由于逻辑运算符OR的优先级比AND低,因此您的WHERE条件实际上等于:

(
    Job.Job Not Like '%4120'
    And Job.Job Not Like '%4235'
    And Job.Job Not Like '%4236'
    And Job.Job Not Like '%5910'
    And Status = 'Active' 
) OR Status = 'Complete' 

这将允许Status'Complete'的任何记录,而与Job的值无关,这不是您想要的。

此外,请注意,可以通过使用字符串函数而不是Not Likein条件而不是Or来简化这些条件。假设您的RDBMS支持right()

right(Job.Job, 4) not in ('4120', '4235', '4236', '5910') 
and Status in ('Complete', 'Active')

答案 1 :(得分:2)

您需要在Status = 'Active' OR Status = 'Complete'周围加上括号,因为现在您的查询执行为:

WHERE (Job.Job Not Like '%4120'
          And Job.Job Not Like '%4235'
          And Job.Job Not Like '%4236'
          And Job.Job Not Like '%5910'
          And Status = 'Active') OR (Status = 'Complete')

因此,无论Status = 'Complete'为何,您都将获得Job.Job处的所有记录。要解决此问题,请尝试在状态检查周围添加括号:

Where(Job.Job Not Like '%4120'
      And Job.Job Not Like '%4235'
      And Job.Job Not Like '%4236'
      And Job.Job Not Like '%5910'
      And (Status = 'Active' OR Status = 'Complete'))

答案 2 :(得分:2)

这是一个括号问题。通过在括号内加入OR,您的意思是“让我将所有与这些字符串匹配且状态为活动或状态为完整的东西-匹配与您的其他条件不匹配的记录。

select Job.Job, Job.Status from Job 
    Where(Job.Job Not Like '%4120'
          And Job.Job Not Like '%4235'
          And Job.Job Not Like '%4236'
          And Job.Job Not Like '%5910')
    And (Status = 'Active' OR Status = 'Complete') 
Order By Job.Job

答案 3 :(得分:1)

如果是sql server,请尝试以下操作:

select Job.Job, Job.Status from Job 
    Where right(rtrim(Job.Job),4) Not in ('4120','4235','4236','5910')
          And Status = 'Active' OR Status = 'Complete') 
    Order By Job.Job

答案 4 :(得分:1)

如果使用in,则不需要括号:

Where Job.Job Not Like '%4120' and
      Job.Job Not Like '%4235' and
      Job.Job Not Like '%4236' and
      Job.Job Not Like '%5910' and
      Status in ('Active', 'Complete') 

或者,如果您的数据库支持left()作为字符串函数:

where left(Job.Job, 4) not in ('4120', '4235', '4236', '5910') and
      Status in ('Active', 'Complete')