前言
数据分析师在提取业务数据的时候,经常会碰到下面的情况。
某项业务数据无法在一个数据库表中完全提取,需要关联一个或者多个数据库表来获取最终的业务数据。这种时候就特别考验数据分析师对数据库表关联的能力。
通过阅读这篇文章,你将收获数据库表关联的四种方式。会以业务场景的角度来讲解数据库表关联的操作。
内连接
小明接到一项数据需求,想查一下最近有哪些用户即买了商品A,又买了商品B。这个时候,小明就需要商品A购买记录、商品B购买记录中关于用户的交集,即求商品A购买记录表与商品B购买记录表的内连接
数据准备:
drop table if exists goods_A_record;
create table
goods_A_record (
user_id int,
spu_id int,
sku_id int,
time timestamp default current_timestamp
) default charset = utf8;
insert into goods_A_record (user_id, spu_id, sku_id) values (223, 23, 45), (223, 23, 41), (333, 11, 12);
drop table if exists goods_B_record;
create table
goods_B_record (
user_id int,
spu_id int,
sku_id int,
time timestamp default current_timestamp
) default charset = utf8;
insert into goods_B_record (user_id, spu_id, sku_id) values (113, 23, 45), (113, 23, 41), (333, 21, 22);
测试:
select A.user_id as user_id from goods_A_record A inner join goods_B_record B on A.user_id = B.user_id;
左连接
第二天,小明接到外部门的另一份数据需求。想知道在社区发表文章的作者,有多少是非车主。
此时,小明要先找找到社区发表文章记录表、车主表。以社区发表文章记录表为主,左连接,count一下有多少行的carOwner字段为null的
数据准备:
drop table if exists article_public_record;
create table article_public_record (
user_id int,
time timestamp default current_timestamp
)default charset = utf8;
insert into article_public_record (user_id) values (112), (113), (114);
drop table if exists carOwner;
create table carOwner(
user_id int,
carType varchar(30),
carVin varchar(30)
)default charset = utf8;
insert into carOwner (user_id, carType, carVin) values (112, 'volvo', '粤A 88888');
测试:
select count(*) from article_public_record a left join carOwner b on a.user_id = b.user_id where b.carType is null;
右连接
第三天早上,小明又接到老板的一个新数据需求。查询一下,有多少车主在社区发表过文章。
此时,小明要先找找到社区发表文章记录表、车主表。以车主表为主,右连接,count一下有多少行的carOwner字段不为null的
数据准备:
drop table if exists article_public_record;
create table article_public_record (
user_id int,
time timestamp default current_timestamp
)default charset = utf8;
insert into article_public_record (user_id) values (112), (113), (114);
drop table if exists carOwner;
create table carOwner(
user_id int,
carType varchar(30),
carVin varchar(30)
)default charset = utf8;
insert into carOwner (user_id, carType, carVin) values (112, 'volvo', '粤A 88888');
测试:
select count(*) from article_public_record a right join carOwner b on a.user_id = b.user_id where a.time is not null;