MySql必知必會實戰練習(三)數據過濾

  在以前的博客MySql必知必會實戰練習(一)表建立和數據添加中完成了各表的建立和數據添加,MySql必知必會實戰練習(二)數據檢索中介紹了全部的數據檢索操做,下面對數據過濾操做進行總結。html

1. where子句操做符

  等於: = 正則表達式

  不等於: != 或 <>post

  小於: <性能

  小於等於: <=ui

  大於: >url

  大於等於:>=3d

  在指定的兩個值之間:BETWEEN  ANDhtm

  空值檢查:is NULLblog

  where組合子句:AND OR IN NOT get

  例:

  select * from products where verd_id in (1001,1002);

  

2. 通配符過濾

  通配符用來匹配值的一部分的特殊字符

  爲在搜索子句中使用通配符,必須使用LIKE操做符,LIKE指示SQL後跟的搜索模式利用通配符匹配而不是直接相等匹配進行比較

  注意:通配符的效率特別低,不要過分使用通配符,不要在搜索模式的開始使用通配符

(1)使用百分號(%)通配符

  select * from products where proc_id like 'ANV%';

  

(2)使用下劃線(_)通配符

  下劃線的用途與%同樣,但下劃線只能匹配單個字符

  select * from products where proc_id like 'ANV0_';

  

3. 使用正則表達式進行搜索

  正則表達式的經常使用方法有不少,這裏不作介紹,主要介紹下REGEXP與LIKE的區別,看下面的例子

  select proc_name from products where proc_name LIKE '1000';

  

  select proc_name from products where proc_name REGEXP '1000';

  

  經過上面會很直接的看到使用LIKE沒有輸出結果,由於LIKE匹配的是整個列,若是被匹配的文本在列值中出現,LIKE將不會找到它,相應的行也不會被返回,而REGEXP在列值內進行匹配,若出現則返回相應的行

  注意:正則表達式匹配特殊字符時必須用\\爲前導,\\.表示查找.

4. 子查詢

  列出訂購物品TNT2的全部客戶信息

  思路:從orderitems表中根據產品名(proc_id)找到訂單號(order_num),再在orders表中根據訂單號找到客戶ID(cust_id),最後再根據客戶ID找到客戶信息

  (1)select order_num,proc_id from orderitems where proc_id = 'TNT2';

  

  (2)select order_num,cust_id from orders where order_num in (20005,20007);

  

  (3)select * from customers where cust_id in (10001,10004);

  

  下面根據子查詢的方式:

  select * from customers where cust_id in (
     select cust_id from orders where order_num in(
        select order_num from orderitems where proc_id = 'TNT2'));

  

  與上面的結果同樣,對於能嵌套的子查詢數量沒有限制,不過再實際使用時因爲性能的限制,不能嵌套太多的子查詢

  方法2:

  select cust_name,cust_address from customers, orders, orderitems where
   customers.cust_id = orders.cust_id AND
   orders.order_num = orderitems.order_num AND
   orderitems.proc_id = "TNT2";

  

  注意:這裏給出的代碼有效並得到所需的結果,可是,使用子查詢並不老是執行這種類型的數據檢索的最有效的方法,最好使用聯結表的方式操做,後面會介紹聯結表方式。

相關文章
相關標籤/搜索