mysql中燕十八:一道面试题使用union all实现两张表id相同的num值相加。

(1)先创建两张表,分别为a,b
create table a (
id char(1),
num int
)engine myisam charset utf8;

insert into a values (‘a’,5),(‘b’,10),(‘c’,15),(‘d’,10);

create table b (
id char(1),
num int
)engine myisam charset utf8;

insert into b values (‘b’,5),(‘c’,15),(‘d’,20),(‘e’,99);
在这里插入图片描述
(2)解决办法:
思路:先把两张表的数据合并到一块,再利用sum来相加
1、使用union
select id, sum(num) from (select * from a union select * from b) as tmp group by id;
在这里插入图片描述
结果出现错误,由于两张表都出现c=15,而union是去重的,所以这里使用union all。
2、使用union all实现结果的不去重
select id, sum(num) from (select * from a union all select * from b) as tmp group by id;
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值