SQL WHERE 条件,为什么使用'a != 7 and b !=836' 的结果不等于'!(a=7 and b=836)'?
SQL WHERE condition, why the result using 'a != 7 and b !=836' is not equal ' !(a=7 and b=836)'?
有如下三个记录:
- a=7 , b=836
- a=8 , b=836
- a=7 , b=839
我想得到没有(a=7 和 b=836)的结果。
像select * from test where a!=7 and b!=836
那样执行sql结果为空,
但它通过使用 select * from test where a<>7 or b<>836
得到了正确的结果。
我有两个问题:
- 为什么 'a!=7 and b!=836' 不等于!(a=7 和 b=836)?
- 这两种情况有什么不同?
'a!=7 and b!=836' 和 'a<>7 or b<>836'
其实!=和<>完全一样。请参阅文档。
<>
是 sql 标准,!=
非标准。
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal
不同之处在于您的逻辑运算符 and
和 or
,以及括号。
select * from test where a!=7 and b!=836
此查询将 select 其中您的两个语句 return 为真,即 a 不是 7,b 不是 836。这 return 什么都没有,有没有这两个都是真的记录。
select * from test where !(a=7 and b=836)
当您将 and
括起来时,您移动了逻辑。该语句意味着所有记录都不匹配 a 为 7 且 b 为 836 的任何记录。因此在括号内它匹配第一条记录,然后它反转 selection.
select * from test where a<>7 or b<>836
<>
等同于!=
(Link to documentation)。但在此查询中,您使用 or
。因此它将匹配任何 a 不是 7 的记录,以及任何不是 836 的记录。因此将匹配第二行和第三行。
如需更多阅读 material,请查看 De Morgan's Laws. !(a and b)
equals !a or !b
. More explanation here and here。
有如下三个记录:
- a=7 , b=836
- a=8 , b=836
- a=7 , b=839
我想得到没有(a=7 和 b=836)的结果。
像select * from test where a!=7 and b!=836
那样执行sql结果为空,
但它通过使用 select * from test where a<>7 or b<>836
得到了正确的结果。
我有两个问题:
- 为什么 'a!=7 and b!=836' 不等于!(a=7 和 b=836)?
- 这两种情况有什么不同? 'a!=7 and b!=836' 和 'a<>7 or b<>836'
其实!=和<>完全一样。请参阅文档。
<>
是 sql 标准,!=
非标准。
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal
不同之处在于您的逻辑运算符 and
和 or
,以及括号。
select * from test where a!=7 and b!=836
此查询将 select 其中您的两个语句 return 为真,即 a 不是 7,b 不是 836。这 return 什么都没有,有没有这两个都是真的记录。
select * from test where !(a=7 and b=836)
当您将 and
括起来时,您移动了逻辑。该语句意味着所有记录都不匹配 a 为 7 且 b 为 836 的任何记录。因此在括号内它匹配第一条记录,然后它反转 selection.
select * from test where a<>7 or b<>836
<>
等同于!=
(Link to documentation)。但在此查询中,您使用 or
。因此它将匹配任何 a 不是 7 的记录,以及任何不是 836 的记录。因此将匹配第二行和第三行。
如需更多阅读 material,请查看 De Morgan's Laws. !(a and b)
equals !a or !b
. More explanation here and here。