表架构:
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运算符不在括号中时提到的日期条件。
答案 0 :(得分:4)
这是因为AND
运算符的higher precedence比OR
高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'
。改为:
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放在括号中。