子查詢總是從內向外處理
書寫子查詢語句時盡量格式化,看起來易理解
使用子查詢的地方可以使用 表聯結 代替
對有歧義的列名進行完全限定,即
where orders.cust_id = customers.cust_id
場景:1、利用子查詢進行過濾
#列出訂購物品tnt2的所有客戶2、作為計算字段使用子查詢第一步:從表
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"
));
#顯示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;
My SQL 使用子查詢
在關係型資料庫中,關係表是把資訊分解成多個表,一類資料乙個表,各表通過某些常用的值互相關聯。在乙個表中通常有乙個外來鍵,包含了和他有關係的表的主鍵,定義了兩個表之間的關係。這裡我們使用兩個表orders和orderitems為例,內容如下 可以看到這兩張表有關聯的是列order item列。想要獲得...
MySQL使用子查詢
子查詢 即巢狀在其他查詢中的查詢 把一條查詢語句的結果用於另一條查詢語句的where子句 select cust id from orders where order num in select order num from orderitems where prod id tnt2 把查詢語句的結...
mysql 使用子查詢 MySQL 子查詢的使用
mysql 子查詢的使用 什麼是子查詢 子查詢是將乙個 select 語句的查詢結果作為中間結果,供另乙個 sql 語句呼叫。像這樣 我們將學生表中的所有班級id當做中間結果 select from t class where c id in select distinct c id from t ...