SQL 学习记录(4 / N)—— left join / right join

当我们要从两张字段不一样的表中分别获取一些数据,拼成一张表导出,可以有多种方式

需求描述:
表1:table_1,记录了用户的 ID(user_id)、曝光内容的 ID(exp_id)
表2:table_2,记录了用户的 ID(user_id)、点击内容的 ID(cli_id)
我们想把每个用户曝光了多少篇内容、点击了多少篇内容整合成一张表导出

我们知道连接这两张表的键应该是 user_id

  1. 使用 where
select a.user_id, count ( a.exp_id), count ( b.cli_id )
from table_1 a, table_2 b
where a.user_id = b.user_id
  1. 使用 left join 或 right join
select a.user_id, count ( a.exp_id), count ( b.cli_id )
from table_1 a
left join table_2 b on a.user_id = b.user_id

那么,left join 和 right join 有啥区别呢?
当 table_1 和 table_2 中的 user_id 不能完全匹配上的时候

  • left join:以左侧的表为「全部匹配」,无论 table_2 中的 user_id 是否跟 table_1 中的都能对应上,我们只取 table_1 中的 user_id。
    • 如果在 table_2 中找不到 table_1 中的 user_id,那么保留 table_1 中的 user_id,但是对应在 table_2 中所取的相应字段,value 为「空」
    • 如果在 table_1 中找不到 table_2 中的 user_id,那么我们忽略 table_2 中多余的 user_id
  • right join:以右侧的表为「全部匹配」,与 left join 正好相反。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值