在不更改第一个表的情况下加入SQL表

时间:2017-05-19 02:38:01

标签: mysql sql left-join

我尝试使用下面的代码将两个表连接在一起,但我希望来自" tab1"保持不变

create table tab3 select * from tab1 left join tab2 on tab1.`tab1`=tab2.`tab2`;

Tab1
a
b
c
d
e
f
g


Tab2
a
a
c
d

但我得到了这个结果," a"从Tab1加倍

Tab1    Tab2
a       a
a       a
b       b
c       c
d       null
e       null
f       null
g       null

我需要这个结果,而Tab1行保持不变,如下表

Tab1    Tab2
a       a
b       b
c       c
d       null
e       null
f       null
g       null

1 个答案:

答案 0 :(得分:1)

效率不高,但您可以使用select distinct

select distinct *
from tab1 left join
     tab2
     on tab1.`tab1` = tab2.`tab2`;

或仅在tab2本身:

select distinct *
from tab1 left join
     (select distinct tab2.* from tab2) tab2
     on tab1.`tab1` = tab2.`tab2`;