2015-02-05 65 views
0

我有以下两个表:从共同行元素两个不同的表中提取数据

Table a: 
name qty 
a  10 
b  20 
c  30 
d  40 

and table b 
name qty 
a  10 
b  20 
d  20 
e  60. 

我想合并有两个表,创建这样

name qty 
a  20 
b  40 
c  30 
d  60 
e  60 

目标的新表如果名称中有相同的值,或者只是将表2中的值附加到表1中,则添加值。

回答

1

不幸的是,MySQL不支持full outer join。下面是使用union allgroup by的方法:

select name, sum(qty) as qty 
from ((select name, qty from a) union all 
     (select name, qty from b) 
    ) ab 
group by name; 
+0

我觉得语法是错误的。你可以检查一下吗? – Morpheus 2015-02-09 12:28:04

+0

@Morpheus。 。 。语法对我来说看起来是正确的。你为什么认为这是错的? – 2015-02-09 21:47:21

0

为了模拟一个完整的外部联接,只是执行一个左外连接(给出表A中的所有行与表B或NULL的所有匹配的行)和右表A为NULL的外部联接(给出表B中没有表A中匹配的所有行 - 匹配已在第一个查询中提供)。

在第一个查询,总是会有从表A与任一数量的值或空值从表B.在第二查询一个数量值,将仅存在从表B.

一个数量值见Fiddle结果。

select a.Name, a.Qty + IsNull(b.Qty, 0) as Qty 
from @TableA a 
left outer join @TableB b 
    on b.Name = a.Name 
union all 
select b.Name, b.Qty 
from @TableA a 
right outer join @TableB b 
    on b.Name = a.Name 
where a.Name is null; 

您可以使用unionunion all具有相同的结果。由于union all需要的处理较少,这就是我选择的。

相关问题