問題描述
我想知道 or/and 是如何工作的?
I am wondering how or/and works?
例如,如果我想獲取 display = 1 的所有行
For example if I want to get all rows where display = 1
我只能做WHERE tablename.display = 1
如果我想要 display = 1 或 2 的所有行
and if I want all rows where display = 1 or 2
我可以做WHERE tablename.display = 1 or tablename.display = 2
但是,如果我想獲取 display = 1 或 2 以及 任何 內容、標簽或標題包含 hello world
But what if I want to get all rows where display = 1 or 2 and where any of the content, tags, or title contains hello world
這個邏輯將如何發(fā)揮作用?
How would the logic play out for that?
Select * from tablename
where display = 1 or display = 2 and content like "%hello world%" or tags like "%hello world%" or title = "%hello world%"
這是我的猜測.但我可以通過多種方式閱讀.
Would be my guess. but then I can read that in several ways.
是否讀出為:
(display = 1 or display = 2) and (content like "%hello world%" or tags like "%hello world%" or title = "%hello world%")
或作為
((display = 1 or display = 2) and (content like "%hello world%")) or (tags like "%hello world%" or title = "%hello world%")
等
推薦答案
MySQL 文檔有一個 良好頁面,其中包含有關哪些運算符優(yōu)先的信息.
The MySQL documentation has a good page with information on which operators take precedence.
從那個頁面,
12.3.1.運算符優(yōu)先級
12.3.1. Operator Precedence
運算符優(yōu)先級如下表所示,從最高優(yōu)先級到最低優(yōu)先級.運營商一起顯示在一行中具有相同的優(yōu)先級.
Operator precedences are shown in the following list, from highest precedence to the lowest. Operators that are shown together on a line have the same precedence.
INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|
= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
BETWEEN, CASE, WHEN, THEN, ELSE
NOT
&&, AND
XOR
||, OR
= (assignment), :=
所以你的原始查詢
Select
*
from tablename
where
display = 1
or display = 2
and content like "%hello world%"
or tags like "%hello world%"
or title = "%hello world%"
會被解釋為
Select
*
from tablename
where
(display = 1)
or (
(display = 2)
and (content like "%hello world%")
)
or (tags like "%hello world%")
or (title = "%hello world%")
如有疑問,請使用括號來明確您的意圖.盡管 MySQL 頁面上的信息很有幫助,但如果再次訪問該查詢,則可能不會立即顯而易見.
When in doubt, use parenthesis to make your intent clear. While the information on the MySQL page is helpful, it may not be immediately obvious if the query is ever revisited.
您可能會考慮以下內容.請注意,我已將 title = "%hello world%"
更改為 title like "%hello world%"
,因為這更符合您描述的目標.
You might consider something like the following. Note that I've changed the title = "%hello world%"
to title like "%hello world%"
, since that fits better with the goal you've described.
Select
*
from tablename
where
(
(display = 1)
or (display = 2)
) and (
(content like "%hello world%")
or (tags like "%hello world%")
or (title like "%hello world%")
)
這篇關于Mysql 或/和優(yōu)先級?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!