简体   繁体   English

将具有不同列和数据的两个表合并

[英]Combine two tables with different columns and data

How can I combine two tables with different data and set value for CompanyC to all data in Table 2 even there is no relationship of CompanyC on Table2.即使Table2上没有CompanyC的关系,如何将两个具有不同数据的表组合起来,并将CompanyC的值设置为表2中的所有数据。

  Table 1:                                 Table 2:

company     jobs                          company     jobs     emp_name
-----------------------------------      ---------------------------------
CompanyA     IT                           CompanyA     IT        John
CompanyB     Business                     CompanyB     Business  Mike
CompanyC     Engineer                     

And the Result Table would be like:结果表如下:

company     jobs            emp_name           
------------------------------------------    
CompanyA     IT                John     
CompanyC     Engineer          John  
CompanyB     Business          Mike      
CompanyC     Engineer          Mike

I already tried this and it is working but the problem is since CompanyC has no data on Table 2. The result will be null.我已经尝试过了,它正在工作,但问题是因为 CompanyC 在表 2 中没有数据。结果将是 null。

select coalesce(t1.company, t2.company)
       t1.jobs, t2.emp_name
from table1 t1 full outer join
     table2 t2
     on t2.name = t1.name;

You can do an INNER join of the tables and use NOT EXISTS in the ON clause like this:您可以对表进行内部INNER ,并在ON子句中使用NOT EXISTS ,如下所示:

SELECT t1.company, t1.jobs, t2.emp_name
FROM Table1 t1 INNER JOIN Table2 t2
ON t2.company = t1.company
OR NOT EXISTS (SELECT 1 FROM Table2 WHERE company = t1.company)

See the demo .请参阅演示
Results:结果:

> company  | jobs     | emp_name
> :------- | :------- | :-------
> CompanyA | IT       | John    
> CompanyC | Engineer | John    
> CompanyB | Business | Mike    
> CompanyC | Engineer | Mike

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM