簡體   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