码迷,mamicode.com
首页 > 其他好文 > 详细

union

时间:2015-10-16 01:00:28      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

union

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;

union

标签:

原文地址:http://www.cnblogs.com/sunznx/p/4884010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!