MYSQL表合并

时间:2011-12-31 17:25:47

标签: mysql

无论如何都要通过C列合并这两个表

表1:

A B C
a b 1
c d 2
e f 3

表2:

C D E
1 G H
4 I J
5 K L

结合

A B C D E
a b 1 G H
c d 2 0 0
e f 3 0 0
0 0 4 I J
0 0 5 K L


我认为加入功能不起作用,因为它不会给你留下C列的所有5个结果?

3 个答案:

答案 0 :(得分:0)

这个在我的测试中起作用:

(SELECT t.a, t.b, t.c, COALESCE(t2.d, 0), COALESCE(t2.e, 0)
    FROM t 
    LEFT JOIN t2 ON t.c = t2.c) 
UNION 
(SELECT 0, 0, t2.c, t2.d, t2.e
    FROM t2 
    LEFT JOIN t ON t2.c = t.c 
    WHERE t.c IS NULL)

测试数据:

Table 1
a  b  c
1  0  1
2  2  2

Table 2
c  d  e
2  0  2
3  0  3

结果

a  b  c  d  e
1  0  1  0  0
2  0  2  0  2
0  0  0  3  3

答案 1 :(得分:0)

这是做FULL OUTER JOIN的最佳示例,但MySQL(AFAIK)不能这样做:

示例数据:

create table tab1 (A char(1), B char(1), C int);
insert into tab1
select 'a', 'b', 1 union all
select 'c', 'd', 2 union all
select 'e', 'f', 3;

create table tab2 (C int, D char(1), E char(1));
insert into tab2
select 1, 'G', 'H' union
select 4, 'I', 'J' union
select 5, 'K', 'L';

Full outer join看起来像这样:

select 
    coalesce(t1.A, '0') as A, 
    coalesce(t1.B, '0') as B, 
    coalesce(t1.C, t2.C) as C, 
    coalesce(t2.D, '0') as D, 
    coalesce(t2.E, '0') as E
from tab1 t1
full outer join tab2 t2 on t1.c = t2.c;

结果(SQL Server):

A    B    C           D    E
---- ---- ----------- ---- ----
a    b    1           G    H
c    d    2           0    0
e    f    3           0    0
0    0    4           I    J
0    0    5           K    L

解决方法是执行unionleft join的{​​{1}}:

right join

结果(MySQL):

select coalesce(t1.A, '0') as A, 
    coalesce(t1.B, '0') as B, 
    coalesce(t1.C, t2.C) as C, 
    coalesce(t2.D, '0') as D, 
    coalesce(t2.E, '0') as E
from tab1 t1
left join tab2 t2 on t1.c = t2.c
union
select coalesce(t1.A, '0') as A, 
    coalesce(t1.B, '0') as B, 
    coalesce(t1.C, t2.C) as C, 
    coalesce(t2.D, '0') as D, 
    coalesce(t2.E, '0') as E
from tab1 t1
right join tab2 t2 on t1.c = t2.c;

答案 2 :(得分:-1)

您想使用UNION而不是JOIN。

请参阅W3schools以获得更好的解释。