SQL必知必会学习笔记9-Kane

九.联结表
将两表通过一个共同点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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值