OR 与 where in mysql 之间的区别

Difference between OR , AND with where in mysql

我在学习Mysql

但看了下面的例子我感到很困惑:

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

此处它返回了用户 table !

中的所有行

(username = 'admin' or true ) 应该是 true 吗?所以哪里是真的

但在这个例子中:

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

它返回了一行(其中用户名 = 'admin')

但是(用户名 = 'admin' 和 true)也应该是 true !

所以有什么区别?

你应该以不同的方式阅读它。

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

阅读如下

(username = 'admin') and (1)

并为或

(username = 'admin') or (1)

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

WHERE 1 
-- this is always true
WHERE 1 

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

现在检查这个 truth table:

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

你应该明白结果。

Mysql 将 1 视为 true 所以这是简单的逻辑 - expression OR true 将始终为真(因此你得到所有行)并且 expression AND true 相当于 expression,所以你只得到满足你条件的rowa

它看起来有点奇怪,但是 mysql 会检查每一行的表达式(包括 1)fpr,即使 1 不是 table 的一部分。它仍然被认为是 wheb 决定是否 select 每行

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