简体   繁体   中英

Difference between OR , AND with where in mysql

i'm learning 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 ? so where true

but in this example :

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

it returned one row (where username = 'admin')

but (username = 'admin' and true) should be true too !

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

If you take

  • x for WHERE username = 'admin' and
  • y for WHERE 1

you should understand the results.

you should read it differently.

the clause checks to see if username equals '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. And condition 2 is always true.

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

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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