1.two kinds of join:innner&outer,outer join包含 left join 和right join。outer join和inner join在实际书写代码中,inner和outer都可以省略。
2.首先我们看下内连接。
select
c.customer_id,
c.first_name,
o.order_id
from customers c
join orders o
on c.customer_id=o.customer_id
order by c.customer_id
3,但是看订单表我们不难发现,其他序号的顾客没有下单Null,如果我们也要显示这些人和对应订单,那么就要用到外连接了。
做法:
1.用left join:join orders o改为left join orders o,其他不变。因此看到左表也就是customer_id(没有null,因此全有)的表,即使没有order_id也会显示。
2.直接用right join:右表中order_id为null的就不会显示。如果想要right join也显示如下结果,则要把orders o和customers c互换位置。
select
c.customer_id,
c.first_name,
o.order_id
from orders o
right join customers c
on c.customer_id=o.customer_id
order by c.customer_id
练习:
生成如下表(部分截图),要求quantity 为null的也要显示
答案:(如果要显示from里面的所有被选内容,就用left join,order by可以不写)
select
p.product_id,
p.name,
oi.quantity
from products p
left join order_items oi
on p.product_id=oi.product_id