1、子查詢:就是嵌套的查詢,用一個查詢的結果作為另一個查詢的條件。
比如要列出訂購了物品“RGAN01”的所有顧客的ID、姓名和聯系人,需要經歷以下幾步
(1)從orderitems中找出訂購了“RGAN01”的所有訂單編號
(2)用(1)的訂單編號在orders中找出顧客的ID
(3)用(2)的顧客ID在customers中找出顧客的姓名和聯系人
書寫SQL語句的時候,從第3步開始寫起,SQL代碼如下:
SELECT cust_id,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 prod_id='RGAN01'));
運行結果如下:
SELECT customers.cust_id,cust_name,cust_contact FROM customers,orders,orderitems WHERE customers.cust_id=orders.cust_id AND orders.order_num=orderitems.order_num AND prod_id='RGAN01';
注意:1.在多個表中有相同的列名(比如customers和orders中都有“cust_id”),必須清楚指明是哪個表的列名;2.WHERE字句不可少,否則就會形成笛卡爾積,左右表的每行都將進行聯接,總行數=表行數的連乘;3.聯接一定要正確
SELECT vend_name,prod_name,prod_price FROM vendors INNER JOIN products ON vendors.vend_id=products.vend_id ORDER BY vendors.vend_id;
SELECT c1.cust_name,c1.cust_contact,c1.cust_email FROM customers c1,customers c2 WHERE c1.cust_name=c2.cust_name AND c2.cust_contact='Jim Jones';
SELECT customers.cust_id,orders.cust_id,orders.order_num FROM customers LEFT OUTER JOIN orders ON customers.cust_id=orders.cust_id;
SELECT customers.cust_id,COUNT(orders.order_num) AS num_ord FROM customers LEFT OUTER JOIN orders ON customers.cust_id=orders.cust_id GROUP BY customers.cust_id;
SELECT cust_name,cust_contact,cust_email FROM customers WHERE cust_state IN('IL','IN','MI') OR cust_name='Fun4All';
改為組合查詢:
SELECT cust_name,cust_contact,cust_email FROM customers WHERE cust_state IN('IL','IN','MI') UNION SELECT cust_name,cust_contact,cust_email FROM customers WHERE cust_name='Fun4All';
其他:UNION默認排除重復的行,若不排除則用UNION ALL;
對UNION結果排序的ORDER BY語句要放到最後
UNION規則:1.可以將多條SELECT語句組合到一起,是否限制數目,取決於DBMS;
2.每個SELECT必須包含相同的列、表達式、聚集函數;
3.同一列的數據類型必須兼容