Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

sql - Combine 2 Tables with different data on each

How can I combine two tables with different data and set value for CompanyC to all data in Table 2 and CompanyD has no relationship on Table 1. I want the Company C to set all data on Table 2.

   T1:                                 T2:

company     jobs                        emp_id  company     jobs     emp_name
-----------------------------------      -------------------------------------
CompanyA     IT                          1      CompanyA     IT        John
CompanyB     Business                    2      CompanyB     Business  Mike
CompanyC     Engineer                    3      CompanyD     Nurse     Mitch

And the result table would be like:

emp_id     company      jobs            emp_name           
----------------------------------------------     
1          CompanyA     IT                John     
1          CompanyC     Engineer          John  
2          CompanyB     Business          Mike      
2          CompanyC     Engineer          Mike
3          CompanyD     Nurse             Mitch
3          CompanyC     Engineer          Mitch

This is what I've tried

 SELECT  t2.emp_id, coalesce(t1.company_name, t2.company_name) AS company_name, 
    coalesce(t1.jobs, t2.jobs) AS jobs, 
    t2.emp_name, 
FROM Table1 t1  
    FULL OUTER JOIN      
    Table2 t2 ON t2.company = t1.company AND t2.jobs = t1.jobs
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simplest logic would be to divide it in small logics and then use union as follows:

Select t2.*
  From t1 join t2 on t1.company = t2.comapny and t1.jobs = t2.jobs
Union
Select t1.company, T2.jobs, T2.emp_name
  From t1 cross join t2
Where not exists (select 1 from t2 t22
                   Where t1.company = t22.comapny and t1.jobs = t22.jobs)
Union 
Select t2.* 
  From t2 where not exists ( select 1 from t1 
                              where t1.company = t2.comapny and t1.jobs = t2.jobs)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...