联合两个具有不同列的表,并在输出中显示null

时间:2017-08-10 16:17:41

标签: mysql sql-server

我有两个表,customer_tbl和suppliers_tbl 如果这两个表的列不同,我如何将这两个表联合起来?

customers_tbl:

http://imgur.com/a/0ATK6

suppliers_tbl:

http://imgur.com/a/6hj3t

这应该是输出:

http://imgur.com/a/0vtiX

我尝试使用union并离开了连接,但它有一个错误。

这是我的代码

select customerid, customername,
       contactname, address,
       city, postalcode, country 
from customer_tbl
left join (select supplierid as customername, 
                  address, city,country 
            from suppliers_tbl) 
  on customertbl_customername = suppliers_tbl.supplierod as customername;

1 个答案:

答案 0 :(得分:0)

对于union,您可以为匹配编号添加空值并键入

select
     customerid
     ,customername
     ,contactname
     ,address
     ,city
     ,country 
     ,postalcode
     from customer_tbl
union 
select 
     supplierid
    ,suppliername
    ,contactname
    ,address
    ,city
    ,country 
    , null
from suppliers_tbl

在您的示例中,您有一些列没有macthing,因此您可以对这些列使用null