(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;