MySQL數據庫入門——where子句,組合where的子句

select語句的where子句指定搜索條件過濾顯示的數據。


1)使用where子句

在 select 語句中,where子句在from子句之後給出,返回滿足指定搜索條件的數據:

select prod_name, prod_price from Products where prod_price = 3.49;

#從Products表中檢索兩個列:prod_name,和prod_price,但條件是隻顯示prod_price值爲3.49的行。


除了上述例子的相等條件判斷,where子句還支持以下條件操作符:
clip_image001

例如,使用<>操作符(或!=)進行不匹配檢查

select vend_id, prod_name from Products where vend_id <> 'DLL01';

#從Products表中顯示vend_id,和prod_name ,但條件是vend_id不是DLL01。


再如,使用between操作符可匹配處於某個範圍內的值。需要指定範圍的端點值:

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子句

(1SQL還允許使用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


4IN操作符

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子句。


5NOT操作符

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子句取反。


(6LIKE操作符

使用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 ]字段的數據。

注:通配符搜索只能用於文本字段(串),非文本數據類型字段不能使用通配符搜索。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章