1. 程式人生 > 其它 >mysql筆記16:建立高階聯結

mysql筆記16:建立高階聯結

  1. 表別名

與列別名不同,表別名只在查詢執行中使用,不返回到客戶機

select cust_name, cust_contact
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 = 'TNT2';

  1. 使用不同型別的聯結

使用表別名的一個理由是,能在單條select語句中不止一次使用相同的表。

2.1 自聯結
自聯結的一個例子:
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.2 自然聯結
沒有重複列

2.3 外部聯結

有時候,某個表的行在另一個表中沒有對應行,如果是內部聯結,則該行不會在結果中出現。但是我們希望該表的每一行都在結果中出現,此時,應當使用外部聯結。
select customers.cust_id, order.num
from customers left out join orders
on customers.cust_id = orders.cust_id;
其中left的含義是指左邊表的每一行都要出現在結果集中。

2.4 使用帶聚集函式的聯結
聯結是可以和聚集函式一同使用的:
select customers.cust_name , customers.cust_id, count(orders.order_num) as num_ord
from customers inner join orders
on customers.cust_id = orders.cust_id
group by customers.cust_id;