联结将一个表中的行与另一个表中的行相关联。如果只需要找出已经关联的行可以用内联结或者等值联结(等值联结也为内联结的一种);若要找出已经关联的行以及未关联的行可以使用外联结:左外连接,右外联结
- 查询已经关联的行:查询购买过商品的顾客以及订单信息
将顾客表中cust_id与订单表中cust_id一致的列进行关联,最后得出结果
SELECT customers.cust_id,orders.order_num
from customers inner join orders
on customers.cust_id = orders.cust_id
- 外联结
左外联结查询左表中的所有数据,即跟右表关联以及不和右表关联的数据
SELECT customers.cust_id,orders.order_num
from customers left outer join orders
on customers.cust_id = orders.cust_id
由结果可以看出先取得左联的所有结果 再到右表中用cust_id进行联结,最终返回左表的所有数据与右边关联的数据以及没有和右表关联的左表数据。右外联结同理
- 联结与聚集函数的使用
计算所有顾客的订单数据,以客户表的cust_id分组
group by的使用:https://blog.youkuaiyun.com/wsdfym/article/details/90671989
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