繁体   English   中英

或之间的区别

[英]Difference between OR , AND with where in mysql

我正在学习Mysql

但是在以下示例之后,我感到困惑:

select * from `users` where username = 'admin' or true;

在这里,它返回了用户表中的所有行!

(用户名='admin'或true)应该为true? 所以真的

但是在这个例子中:

select * from `users` where username = 'admin' and true;

它返回了一行(其中username ='admin')

但是(username ='admin'和true)也应该为true!

那有什么区别?

-- this is always true
WHERE 1 

-- this is only true for rows where the username is admin
WHERE username = 'admin'

现在检查这个真值表

x  y | x and y | x or y
-----------------------
F  F |    F    |   F
F  T |    F    |   T
T  F |    F    |   T
T  T |    T    |   T

https://en.wikipedia.org/wiki/Boolean_algebra

如果你拿

  • x代表WHERE username = 'admin'
  • y对于WHERE 1

您应该了解结果。

您应该以不同的方式阅读。

该子句检查用户名是否等于“ admin”。

阅读如下

(username = 'admin') and (1)

和或

(username = 'admin') or (1)

因此第二个将返回数据库中的所有值,因为它检查是否满足条件1或2。 条件2始终为真。

WHERE 1 

Mysql认为1为true因此它是简单的逻辑- expression OR true始终为true(因此您可以获得所有行),而expression AND true等效于expression ,因此您仅获得满足条件的行

看起来有点奇怪,但是mysql每行都会检查fpr的扩展(包括1),即使1不是表的一部分。 仍然考虑决定是否选择每一行

In a room there are 10 people.
1 is a woman, the rest are men.

How many in the room are People OR Women = 10. 
How many in the room are People AND Women = 1. 
How many in the room are People AND Men = 9. 
How many in the room are Men OR Women = 10. 
How many in the room are Men AND Women = 0.       
  In todays day and age, this is questionable ;)

Still I hope it helps

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM