简体   繁体   English

或之间的区别

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

i'm learning Mysql 我正在学习Mysql

but i felt confused after the examples below : 但是在以下示例之后,我感到困惑:

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

here it returned all the rows in users table ! 在这里,它返回了用户表中的所有行!

(username = 'admin' or true ) should be true ? (用户名='admin'或true)应该为true? so where true 所以真的

but in this example : 但是在这个例子中:

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

it returned one row (where username = 'admin') 它返回了一行(其中username ='admin')

but (username = 'admin' and true) should be true too ! 但是(username ='admin'和true)也应该为true!

so what's is the difference? 那有什么区别?

-- this is always true
WHERE 1 

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

Now check this 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 https://en.wikipedia.org/wiki/Boolean_algebra

If you take 如果你拿

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

you should understand the results. 您应该了解结果。

you should read it differently. 您应该以不同的方式阅读。

the clause checks to see if username equals 'admin'. 该子句检查用户名是否等于“ admin”。

read it as follows 阅读如下

(username = 'admin') and (1)

and for the or 和或

(username = 'admin') or (1)

so the second will return all values in your db, because it checks if condition 1 or 2 is met. 因此第二个将返回数据库中的所有值,因为它检查是否满足条件1或2。 And condition 2 is always true. 条件2始终为真。

WHERE 1 

Mysql considers 1 as true so it is simple logic- expression OR true will always be true (so you get all rows) and expression AND true is equivalent to expression , so you get only the rowa that meets your condition Mysql认为1为true因此它是简单的逻辑- expression OR true始终为true(因此您可以获得所有行),而expression AND true等效于expression ,因此您仅获得满足条件的行

It looks a bit wierd, but mysql checks the expreesion (including the 1) fpr every row, even though 1 is not part of the table. 看起来有点奇怪,但是mysql每行都会检查fpr的扩展(包括1),即使1不是表的一部分。 It is still considered wheb decideling whether to select each row 仍然考虑决定是否选择每一行

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