九.联结表
将两表通过一个共同点key联结,而不用在一个表内储存太多重复的信息。
- 创建联结
指定要联结的表及关联他们的方式。
select vend_nanme, prod_name, prod_price
from Vendors, Products
where vendors.vend_id = products.vend_id;
#这一句很重要!
#如果没有这一句完全限定列名进行联结,检索的结果将是笛卡尔积,数量等于表1的结果数*表2的结果数
#这种结果叫叉联结(cross join)
以上方法叫做内联结(inner join)
这种语句也可写成:
select vend_name, prod_name, prod_price
from Vendors INNER JOIN Products
ON vendors.vend_id = products.vend_id
#与第一种是一样的效果
同样SQL可以用select语句联结多个(>2)列表,但在联结时一定要将各类表都考虑到
- 使用表别名
给表取别名以方便实用
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 = 'RGAN01';
但是表别名只能在查询执行的时候使用,与列名不同,表明不返回到客户端
- 自联结
而联结查询也联结两个完全一样的表,并用别名区分它们:
select c1.cust_id, c1.cust_name, c1.cust_contact
from customers as c1, customers as c2
where c1.cust_name = c2.cust_name
and c2.cust_contact = 'Jim Jones';
#DBMS先按c2过滤出想要的cust_name再 在c1中找到它所有的contact的信息
- 外联结
将一个表中的行与另一个表中没有关联行的哪些行关联,
使用LEFT或RIGHT表示选择在OUTER JOIN符左边或右边的表中的所有行,
FULL OUTER JOIN 表示检索左右两表的所有行并关联那些可以关联的行;
select customers.cust_id, orders.order_num
from customers LEFT OUTER JOIN orders
on customers.cust_id = orders.cust_id;
#无匹配的行用NULL表示出来
- 使用带聚集函数的联结
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;