具有OR条件的同一列上的多个NOT LIKE运算符在SQL中失败

时间:2014-03-22 18:04:06

标签: sql sql-server

表架构:

CREATE TABLE [dbo].[Message](
    [id] [int] NOT NULL,
    [created_on] [datetime] NULL,
    [message] [nvarchar](max) NULL,
 CONSTRAINT [PK_Message] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)
) ON [PRIMARY]

值:

1   '2013-01-01 00:00:00.000'   'error occured "BASKET_BALL"'
2   '2014-01-01 00:00:00.000'   'error occured "FOOT_BALL"'
3   '2012-01-01 00:00:00.000'   'I am not involved in like operator'
4   '2014-02-01 00:00:00.000'   'I might be involved'

查询表格的回复:

SELECT 
    ID,CREATED_ON,MESSAGE 
FROM 
    MESSAGE
WHERE 
    MESSAGE NOT LIKE '%"FOOT_BALL"%' OR MESSAGE NOT LIKE '%BASKET_BALL%'
    AND CREATED_ON >= '2014-01-01'

输出:

1   2013-01-01 00:00:00.000 error occured "BASKET_BALL"
2   2014-01-01 00:00:00.000 error occured "FOOT_BALL"
3   2012-01-01 00:00:00.000 I am not involved in like operator
4   2014-02-01 00:00:00.000 I might be involved

问题:

有人可以解释为什么在明确提到日期条件超过2014时查询会返回所有表值吗?我理解通过将消息条件保持在括号中它会产生正确的结果。但是,想知道为什么sql排除了当not like运算符不在括号中时提到的日期条件。

2 个答案:

答案 0 :(得分:4)

这是因为AND运算符的higher precedenceORSELECT ID,CREATED_ON,MESSAGE FROM MESSAGE WHERE (MESSAGE NOT LIKE '%"FOOT_BALL"%' OR MESSAGE NOT LIKE '%BASKET_BALL%') AND CREATED_ON >= '2014-01-01' 。改为:

    MESSAGE NOT LIKE '%"FOOT_BALL"%' OR (MESSAGE NOT LIKE '%BASKET_BALL%'
    AND CREATED_ON >= '2014-01-01')

根据您的需要,括号可以围绕后一部分,如下所示:

{{1}}

答案 1 :(得分:1)

您缺少括号,因此具有较低优先级的OR转换为

WHERE 
MESSAGE NOT LIKE '%"FOOT_BALL"%' OR (MESSAGE NOT LIKE '%BASKET_BALL%'
AND CREATED_ON >= '2014-01-01')

MESSAGE NOT LIKE '%"FOOT_BALL"%' 

返回3行,不关心日期

将两个OR放在括号中。