創建聯結
1、where聯結
select vend_name, prod_name, prod_price
from vendors, products
where vendors.vend_id = products.vend_id
order by vend_name, prod_name;
結果:
\1.PNG
注意:這里如果省略where條件,會返回笛卡爾積結果
2、內部聯結 inner join
select vend_name, prod_name, prod_price
from vendors inner join products
on vendors.vend_id = products.vend_id;
說明:這個例子返回的結果跟上一個例子完全一致。
上面兩種寫法,ANSI SQL規范首選inner join語法。
此外,盡管使用where字句定義聯結的確比較簡單,但是使用明確的聯結語法能夠確保不會忘記聯結條件,有時候這樣做也能影響性能。
3、聯結多個表
SQL對一條select語句中可以聯結的表的數目沒有限制。創建聯結的基本規則也相同。首先列出所有表,然后定義表之間的關系。
例如:
select prod_name, vend_name, prod_price, quantity
from orderitems, products, vendors
where products.vend_id = vendors.vend_id
and orderitems.prod_id = products.prod_id
and order_num = 20005;
\2.PNG
說明:此例子顯示編號為20005的訂單中的物品。
之前曾有過一個例子,可以用聯結表的方式改寫:
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 prod_id='TNT2'));
select cust_name, cust_contact
from customers, orders, orderitems
where customers.cust_id = orders.cust_id
and orderitems.order_num = orders.order_num
and prod_id = 'TNT2';
使用不同類型的聯結
上面我們使用的只是稱為內部聯結或等值聯結的簡單聯結。下面介紹3中其他聯結。
1、自聯結
假如你發現某物品(其ID為DTNTR)存在問題,因此想知道生產該物品的供應商生產的其他物品是否有問題。
//使用子查詢的方式實現
select prod_id, prod_name
from products
where vend_id = (select vend_id
from products
where prod_id = 'DTNTR');
//使用自聯結的方式
select p1.prod_id, p1.prod_name
from products as p1, products as p2
where p1.vend_id = p2.vend_id
and p2.prod_id = 'DTNTR';
自聯結通常作為外部語句用來替代從相同表中檢索數據時使用的子查詢語句。雖然最后的結果是相同的,但有時處理聯結遠比處理子查詢快得多。
2、自然聯結
自然聯結排除多次出現。使每列只返回一次。
自然聯結是這樣一種聯結,其中你只能選擇那些唯一的列。
舉例:
select c.*, o.order_num, o.order_date, oi.prod_id, oi.quantity, oi.item_price
from customers as c, orders as o, orderitems as oi
where c.cust_id = o.cust_id
and oi.order_num = o.order_num
and prod_id = 'FB';
3、外部聯結
許多聯結將一個表中的行與另一個表中行相聯結。但有時候會需要包含沒有關聯行的那些行。
舉例:
select customers.cust_id, orders.order_num
from customers left outer join orders
on customers.cust_id = orders.cust_id;
結果:
\3.PNG
使用帶聚集函數的聯結
舉例:
select customers.cust_name
customers.cust_id
count(orders.order_num) as num_ord
from customers left join orders
on customers.cust_id = orders.cust_id
group by customers.cust_id;
結果:
\4.PNG
參考書籍:
- MySQL必知必會