mysql括號被過濾 MySQL之資料過濾

2021-10-18 22:25:40 字數 1689 閱讀 3085

資料過濾:如何組合where子句以建立功能更強的更高階的搜尋條件。還將學習如何使用not和in操作符。

1. and操作符

-- and操作符select vend_id, prod_id, prod_price, prod_name

from products

where vend_id = 1003 and prod_price <= 10;and: 用在where子句中的關鍵字,用來指示檢索滿足所有給定條件的行。

2. or操作符

-- or操作符select prod_name, prod_price

from products

where vend_id = 1002 or vend_id = 1003;or:where子句中使用的關鍵字,用來表示檢索匹配任一給定條件的行。

3.計算次序

-- 計算次序select prod_name, prod_price

from products

where vend_id = 1002 or vend_id = 1003 and prod_price >= 10;

-- 計算出來的結果可能跟你想的不太一樣。為什麼會這樣呢?原因在於計算的次序。-- sql先執行了vend_id = 1003 and prod_price >= 10,然後才執行了or操作。-- 換句話說,and在計算次序中優先順序更高。

-- 正確的方法是加圓括號select prod_name, prod_price

from products

where (vend_id = 1002 or vend_id = 1003) and prod_price >= 10;在where子句中使用圓括號:任何時候使用具有and和or操作符的where子句,都應該使用圓括號明確地分組操作符。不要過分依賴預設計算次序,即使它確實是你想要的東西也是如此。使用圓括號沒有什麼壞處,它能消除歧義。

4. in操作符in操作符用來指定條件範圍,範圍中的每個條件都可以進行匹配。in取合法值的由逗號分隔的清單,全都括在圓括號中。

-- in操作符select prod_name, prod_price

from products

where vend_id in (1002,1003)

order by prod_name;如果你認為in操作符完成與or相同的功能,那麼你的這種猜測是對的。下面的sql語句完成與上面的例子相同的工作。

select prod_name, prod_price

from products

where vend_id=1002 or vend_id=1003

order by prod_name;為什麼要使用in操作符?其優點具體如下。

1.在使用長的合法選項清單時,in操作符的語法更清楚且更直觀。

2.在使用in時,計算的次序更容易管理(因為使用的操作符更少)。

3. in操作符一般比or操作符清單執行更快。

4. in的最大優點是可以包含其他select語句,使得能夠更動態地建 立where子句。

5. not操作符not:where子句中用來否定後跟條件的關鍵字。

-- not操作符select prod_name, prod_price

from products

where vend_id not in (1002,1003)

order by prod_name;

參考:《mysql必知必會》

mysql過濾資料 MySQL過濾資料

1.mysql過濾資料 使用where子句 select prod name,prod price from products where prod price 2.50 檢查單個值 select prod name,prod price from products where prod name ...

mysql過濾範圍 MySQL 過濾資料

使用select語句的where子句指定搜尋條件 在select語句中,資料根據where子句中指定的搜尋條件進行過濾,where子句在表名之後給出 select 列名1,列名2 from 表名 where 條件 條件為列中資料的特定值 where子句位置 select from where ord...

mysql過濾 MySQL必知必會 資料過濾

組合where子句 1.1 and操作符 1.2 or操作符 1.3 計算次序 in 操作符 not操作符 1.1 and操作符 mariadb test select id,age,province from user where age 30 and province 北京 id age pro...