联结表

一些定义

联结(join)

将数据分成多个表进行有效的存储,并通过外键联结彼此。

联结的好处
  • 方便处理;
  • 有更大的可伸缩性;(能够适应不断增加的工作量而不失败)
笛卡尔积

一个表和另一个表的交叉相乘,返回的行数是一个表的行数乘以另一表的行数

创建联结

select vend_name,prod_name,prod_price 
from vendors,products 
where vendors.vend_id=products.vend_id;//等值联结

没有联结条件(where子句)的表返回的是笛卡尔积。

内部联结(inner join)

使用关键字inner join,后面联结条件前不用where用on

select vend_name,prod_name,prod_price 
from vendors inner join products 
on vendors.vend_id=products.vend_id;
=select vend_name,prod_name,prod_price 
from vendors natural join products 
where vendors.vend_id=products.vend_id;//自然联结,至少应该有一行出现在不止一个表中

外部联结

该联结包含了哪些在相关表中没有关联行的行

table1 left (outer) join table2 on...
=table2 right (outer) join table1 on...//left和right表示指定哪边的表检索所有行

自联结

替代从相同表中检索数据的子查询

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

使用带聚集函数的联结

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;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容