题目要求
A表:
id | num |
a | 5 |
b | 10 |
c | 20 |
d | 15 |
B表:
id | num |
b | 15 |
c | 20 |
d | 30 |
e | 35 |
要求得到
id | num |
a | 5 |
b | 25 |
c | 40 |
d | 45 |
e | 35 |
答案代码:
create table a (
id char(1) primary key,
num int not null default 0
)engine myisam charset utf8;
create table b(
id char(1) primary key,
num int not null default 0
)engine myisam charset utf8;
select id,sum(num) from
(select * from a
union all
select * from b)
as temp
group by id;
要点:
1.union用法的注意事项(列的对应,union all 与union的区别(去重与否));
2.from子查询的用法(as 别名的使用);
3.group by与聚合函数的搭配使用。