
本節(jié)將介紹如何組合 where 子句以建立功能更強(qiáng)的更高級的搜索條件
組合 where 子句
and 操作符
select *
from sc
where score > 60 and score < 80;
此 sql 語句檢索 sc 表中 score 字段值大于 60 并且小于 80 的所有數(shù)據(jù),輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 02 | 01 | 70.0 |
| 04 | 01 | 72.0 |
| 05 | 01 | 76.0 |
+------+------+-------+
上述例子中使用了只包含一個關(guān)鍵字 and 的語句,把兩個過濾條件組合在一起。還可以添加多個過濾條件,每添加一條就要使用一個 and
or 操作符
select *
from sc
where score = 70 or score = 80;
此 sql 語句檢索 sc 表中 score 字段等于 70 或 等于 80 的所有數(shù)據(jù),輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 01 | 01 | 80.0 |
| 02 | 01 | 70.0 |
| 02 | 03 | 80.0 |
| 03 | 01 | 80.0 |
| 03 | 02 | 80.0 |
| 03 | 03 | 80.0 |
+------+------+-------+
計算次序
where 可包含任意數(shù)目的 and 和 or 操作符。允許兩者結(jié)合以進(jìn)行復(fù)雜和高級的過濾
select *
from sc
where score = 70 or score = 80 and sid =1;
輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 01 | 01 | 80.0 |
| 02 | 01 | 70.0 |
+------+------+-------+
以上例子可以看出 sql(像多數(shù)語言一樣)在處理 or 操作符前,優(yōu)先處理 and 操作符,如果想優(yōu)先處理 or 語句,則應(yīng)改為:
select *
from sc
where (score = 70 or score = 80) and sid =1;
輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 01 | 01 | 80.0 |
+------+------+-------+
in 操作符
圓括號的另一種寫法可以使用 in 操作符來代替,in 操作符用來指定條件范圍,范圍中的每個條件都可以進(jìn)行匹配
select *
from sc
where score in (70,80)
order by cid;
此 sql 語句檢索 sc 表中 score 字段值為 70 和 80 的所有數(shù)據(jù),并按照 cid 的升序排序,輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 01 | 01 | 80.0 |
| 02 | 01 | 70.0 |
| 03 | 01 | 80.0 |
| 03 | 02 | 80.0 |
| 02 | 03 | 80.0 |
| 03 | 03 | 80.0 |
+------+------+-------+
使用 in 的優(yōu)點(diǎn):
1.在使用長的合法選項清單時, in 操作符的語法更清楚且更直觀
2.在使用 in 時,計算的次序更容易管理(因為使用的操作符更少)
3.in 操作符一般比 or 操作符清單執(zhí)行更快
4.in 的最大優(yōu)點(diǎn)是可以包含其他 select 語句,使得能夠更動態(tài)地建立 where 子句
not 操作符
where 子句中的 not 操作符有且只有一個功能,那就是否定它之后所跟的任何條件
select *
from sc
where score in (70,80)
order by cid;
輸出為:
+------+------+-------+
| SId | CId | score |
+------+------+-------+
| 04 | 01 | 72.0 |
| 05 | 01 | 76.0 |
| 06 | 01 | 31.0 |
| 01 | 02 | 40.0 |
| 02 | 02 | 60.0 |
| 04 | 02 | 59.0 |
| 05 | 02 | 87.0 |
| 07 | 02 | 89.0 |
| 01 | 03 | 99.0 |
| 04 | 03 | 59.0 |
| 06 | 03 | 34.0 |
| 07 | 03 | 98.0 |
+------+------+-------+
Mysql 支持使用 not 對 in 、 between 和 exists 子句取反,這與多數(shù)其他 dbms 允許使用 not 對各種條件取反有很大的差別