Mysql数据库表join方式

前言

数据分析师在提取业务数据的时候,经常会碰到下面的情况。
某项业务数据无法在一个数据库表中完全提取,需要关联一个或者多个数据库表来获取最终的业务数据。这种时候就特别考验数据分析师对数据库表关联的能力。
通过阅读这篇文章,你将收获数据库表关联的四种方式。会以业务场景的角度来讲解数据库表关联的操作。

内连接

小明接到一项数据需求,想查一下最近有哪些用户即买了商品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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值