mysql_使用子查詢

子查詢總是從內向外處理
書寫子查詢語句時儘量格式化,看起來易理解
使用子查詢的地方可以使用 表聯結 代替
對有歧義的列名進行完全限定,即where orders.cust_id = customers.cust_id
 
場景:
1、利用子查詢進行過濾
#列出訂購物品TNT2的所有客戶
第一步:從表orderitems中檢查包含物品TNT2的所有訂單的編號
第二步:從表orders中根據第一步查到的訂單編號找到客戶id號
第三部:從表customers中根據第二步中查到的客戶id找到客戶信息
select cust_name,cust_contact
from customers
where cust_id in (select cust_id
                  from orders
                  where order_num in (select order_num
                                      from orderitems
                                      where pro_id="TNT2"));
2、作爲計算字段使用子查詢
#顯示customers表中每個客戶的訂單總數
第一步:從表customers表檢索出所有的客戶
第二步:針對第一步檢索出的每個客戶,統計其在orders表中的訂單總數
select cust_name,cust_state,(select count(*)
                             from orders
                             where orders.cust_id = customers.cust_id) as num
from customers
order by cust_name;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章