select語句的where子句指定搜索條件過濾顯示的數據。ide
(1)使用where子句spa
在 select 語句中,where子句在from子句以後給出,返回知足指定搜索條件的數據:blog
select prod_name, prod_price from Products where prod_price = 3.49;排序
#從Products表中檢索兩個列:prod_name,和prod_price,但條件是隻顯示prod_price值爲3.49的行。ip
除了上述例子的相等條件判斷,where子句還支持如下條件操做符:get
例如,使用<>操做符(或!=)進行不匹配檢查:it
select vend_id, prod_name from Products where vend_id <> 'DLL01';class
#從Products表中顯示vend_id,和prod_name ,但條件是vend_id不是DLL01。cli
再如,使用between操做符可匹配處於某個範圍內的值。須要指定範圍的端點值:select
select prod_name, prod_price from Products where prod_price between 5.99 and 9.49;
# 從Products表中顯示prod_name, prod_price,可是條件是價格在5.99美圓和9.49美圓之間 (包括5.99美圓和9.49美圓)
(2)組合where子句
(1)SQL還容許使用and或or操做符組合出多個where子句,例如使用and操做符:
select prod_id, prod_price, prod_name from Products where vend_id = 'DLL01' AND prod_price <= 4;
#從Products表中顯示 prod_id, prod_price和prod_name,可是條件是vend_id爲DLL01和prod_price小於等於4(兩個條件必須所有知足)
(2)同理,可以使用OR操做符檢索匹配任一條件的行:
select prod_name, prod_price from Products where vend_id = 'DLL01' OR vend_id = 'BRS01';
#從Products表中顯示prod_name和prod_price,可是條件是vend_id爲DLL01或者是vend_id爲BRS01(只需知足任一條件便可)
(3)求值順序
where子句容許包含任意數目的and和or操做符以進行復雜、高級的過濾。但須要注意求值順序:and操做符優先級高於or操做符,但可使用圓括號明確地指定求值順序:
select prod_name, prod_price from Products where (vend_id = 'DLL01' or vend_id ='BRS01') and prod_price <= 10;
#從Products表中顯示prod_name和prod_price,可是條件是(vend_id爲DLL01或者是vend_id爲BRS01)同時prod_price小於等於10
(4)IN操做符
IN操做符用來指定條件範圍,範圍中的每一個條件均可以進行匹配。條件之間用逗號分隔:
select prod_name, prod_price from Products where vend_id in ( 'DLL01', 'BRS01' ) order by prod_name;
#從Products表中顯示prod_name和prod_price,可是條件是(vend_id爲DLL01和vend_id爲BRS01)按照 prod_name排序。
注:IN操做符完成了與OR相同的功能,但與OR相比,IN操做符有以下優勢:
- 有多個條件時,IN操做符比一組OR操做符更清楚直觀且執行得更快;
- 在與其餘AND和OR操做符組合使用IN時,求值順序更容易管理;
- IN操做符的最大優勢是能夠包含其餘SELECT語句,能動態地創建WHERE子句。
(5)NOT操做符
NOT操做符用來否認跟在它以後的條件:
select vend_id,prod_name from Products where not vend_id = 'DLL01' order by prod_name;
#從Products表中顯示 vend_id和prod_name ,可是條件是除了vend_id爲DLL01,按照 prod_name排序。
上面的例子也可使用<>操做符來完成。但在更復雜的子句中,NOT是很是有用的。例如,在與IN操做符聯合使用時,NOT能夠很是簡單地找出與條件列表不匹配的行:
select vend_id,prod_name from Products where vend_id not in ( 'DLL01', 'BRS01' ) order by prod_name;
#從Products表中顯示 vend_id和prod_name ,可是條件是除了vend_id爲DLL01,按照 prod_name排序。
注:和多數其餘 DBMS容許使用 NOT 對各類條件取反不一樣,MySQL支持使用 NOT 對 IN 、 BETWEEN 和EXISTS子句取反。
(6)LIKE操做符
使用LIKE操做符和通配符能夠進行模糊搜索,以便對數據進行復雜過濾。最常使用的通配符是百分號( % ),它能夠表示任何字符出現任意次數:
select prod_id, prod_name from Products where prod_name like '%bean bag%';
#從Products表中顯示 prod_id和prod_name ,可是條件是prod_name的行中含有[bean bag]字段的數據。
另外一個有用的通配符是下劃線(_)。它的用途與%同樣,但只匹配單個字符,而不是多個或0個字符:
select prod_id, prod_name from Products where prod_name like '_ inch teddy bear';
#從Products表中顯示 prod_id和prod_name ,可是條件是prod_name的行中含有[ _ inch teddy bear ]字段的數據。
注:通配符搜索只能用於文本字段(串),非文本數據類型字段不能使用通配符搜索。