union
A 表: B 表: | id | num | | id | num | +------+------+ +------+------+ | a | 5 | | b | 5 | | b | 5 | | c | 15 | | c | 15 | | d | 20 | | d | 10 | | e | 99 |
要求查询出以下效果:
| id | num | +------+----------+ | a | 5 | | b | 10 | | c | 30 | | d | 30 | | e | 99 |
drop table if exists a; create table a ( id char(1), num int )engine myisam charset utf8; insert into a values (‘a‘, 5), (‘b‘, 5), (‘c‘, 15), (‘d‘, 10); drop table if exists b; create table b ( id char(1), num int )engine myisam charset utf8; insert into b values (‘b‘, 5), (‘c‘, 15), (‘d‘, 20), (‘e‘, 99);
select * from ((select id, num from a) union (select id, num from b)) order by id; -- 报错, Every derived table must have its own alias select * from ((select id, num from a) union (select id, num from b)) as tmp order by tmp.id;
select id, sum(num) as num from ((select id, num from a) union (select id, num from b)) as tmp group by tmp.id; -- 错误,A 表的 (b,5) 和 B 表的 (b,5) 被重合 select id, sum(num) as num from ((select id, num from a) union all (select id, num from b)) as tmp group by tmp.id;