Code with MOSH 3

本文解释了SQL中的隐式和显式JOIN语法,重点讲解了INNERJOIN、LEFTJOIN、RIGHTJOIN和OUTERJOIN的区别,以及在处理多表连接时如何选择合适的连接类型。通过实例展示了如何在实际场景中应用这些连接方式。

Implicit Join Syntax

lmplicit
SELECT *
FROM orders o, customers c 
WHERE o.customer_id = c.customer_id


上下两个代码是等价的 ,

select * 
FROM orders o
JOIN customers c 
ON o.customer_id = c.customer_id 

outer join

left join

当使用join连接时,当c.customer_id = o.customer_id时, 表中只会出现两表中customer_id 相等的数据, 那些没有购买订单的顾客不会出现在表中,但我需要所有顾客的id都在表中时,需要用到left join。 其是指左表中所有的信息都会存在(这个例子中就是左表所有的customer_id 都会有,无论是否购买了订单)。  什么是左表呢,FROM 后面的表就是左表,join 后的是右表。

SELECT 
	 c.customer_id,
     c.first_name,
     o.order_id
FROM customers c
left join orders o
	 ON c.customer_id = o.customer_id
ORDER BY c.customer_id   
	

Rihgt join

same with left join, whether condition is satisfied or not, all the information of right table will appear.  

练习

查询上述表,(用order_items 和product表拼)

SELECT 
      p.product_id,
      p.name,
      oi.quantity
FROM products p
LEFT JOIN  order_items oi
		ON p.product_id = oi.product_id
ORDER BY p.product_id

因为表中包含了所有的product_id,所以肯定是需要product表中的product_id,因为order表中,不一定所有的product都会被购买。 需要使用left join 将product表中所有的id,都记录。

Out join between Multiple Tables

SELECT 
	 c.customer_id,
     c.first_name,
     o.order_id,
	 sh.name as shipper
FROM customers c
LEFT join orders o
	 ON c.customer_id = o.customer_id
LEFT JOIN shippers sh 
	 ON sh.shipper_id = o.shipper_id 
ORDER BY c.customer_id   
	

练习

完成上列查询

SELECT 
	 o.order_date,
     o.order_id,
     c.first_name as custmoer,
     sh.name as shipper,
     os.name as status
FROM orders o
JOIN customers c 
	 ON	 o.customer_id = c.customer_id
LEFT JOIN shippers sh
     ON o.shipper_id = sh.shipper_id 
 JOIN order_statuses os
	 ON o.status = os.order_status_id
 

四表连接 三个join。 第一个join,因为每一个order 都有一个customer id, 条件永远成立,inner join is ok。 Second join, 因为,不是所有的order 都有 shipper id,因为有些订单没发货,所以此处要用左连接,将order表中,那些空值也要出现在表中,也就是需要左表的所有id 信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值