前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >第12-13课 创建表的联结创建联结内联结联结多个表外联结自联结使用带聚集函数的联结小结

第12-13课 创建表的联结创建联结内联结联结多个表外联结自联结使用带聚集函数的联结小结

作者头像
desperate633
发布2018-08-22 11:35:45
5700
发布2018-08-22 11:35:45
举报
文章被收录于专栏:desperate633desperate633

sql中最强大的功能之一就是表的联结。

为什么使用联结? 因为在关系表中,数据是存储在各个表中的。如何一次检索出各个表中的数据,答案就是使用联结啦。

创建联结

select vend_name, prod_name,prod_price
from vendors,products
where vendors.vend_id = products.vend_id;

注意,联结产生的是笛卡尔积,所以需要使用where语句。

内联结

就是上一段代码中的等值联结,基于两个表之间的相等测试。

select vend_name, prod_name,prod_price
from vendors inner join products
on vendors.vend_id = products.vend_id;

联结多个表

显示订单2007中的物品:

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 = 20007;

使用联结实现十一课中的例子:

 select cust_name, cust_contact
 from customers, orders,orderitems
 where orders.cust_id = customers.cust_id
 and orders.order_num = orderitems.order_num
and prod_id = 'RGAN01';

外联结

外联结用来处理那些需要包括没有关联的那些行的查询 比如: 对每个顾客下的订单进行计数,包括哪些至今尚未下订单的顾客

select customers.cust_id, orders.order_num
from customers left outer join orders
on customers.cust_id = orders.cust_id;
select customers.cust_id, orders.order_num
from customers right outer join orders
on customers.cust_id = orders.cust_id;

自联结

同一个表自己跟自己的联结

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';

使用带聚集函数的联结

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;

小结

  • 注意联结的类型,大多数情况都是内联结,偶尔用到外联结
  • 必须提供联结条件,不然得出的是笛卡尔积,里面包含了不正确的数据
  • 在一个联结中可以包含多个表
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.01.08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 创建联结
  • 内联结
  • 联结多个表
  • 外联结
  • 自联结
  • 使用带聚集函数的联结
  • 小结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档