当我们要从两张字段不一样的表中分别获取一些数据,拼成一张表导出,可以有多种方式
需求描述:
表1:table_1,记录了用户的 ID(user_id)、曝光内容的 ID(exp_id)
表2:table_2,记录了用户的 ID(user_id)、点击内容的 ID(cli_id)
我们想把每个用户曝光了多少篇内容、点击了多少篇内容整合成一张表导出
我们知道连接这两张表的键应该是 user_id
- 使用 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
- 使用 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 正好相反。