理想情况下对于这些类型的情况FULL OUTER JOINS
很有用 - 但显然 MySQL 不支持FULL OUTER JOINS
请参阅: MySQL 中的完全外部连接
更新(不使用右外连接):
create table table1
(month int
,salesperson_assigned int
,Product1_revenue int);
create table table2
(month int
,salesperson_assigned int
,Product2_revenue int);
insert into table1 values(1,10,100);
insert into table1 values(2,10,200);
insert into table1 values(1,11,40);
insert into table1 values(2,11,800);
insert into table1 values(3,11,400);
insert into table2 values(1,10,100);
insert into table2 values(2,10,200);
insert into table2 values(1,12,40);
insert into table2 values(2,12,200);
select
table1.month
,table1.salesperson_assigned
,ifnull(table1.Product1_revenue,0) as Product1_revenue
,ifnull(table2.Product2_revenue,0) as Product2_revenue
,ifnull(table1.Product1_revenue,0)+ifnull(table2.Product2_revenue,0) as total_revenue
from table1
left outer join table2
on table1.salesperson_assigned=table2.salesperson_assigned and table1.month=table2.month
union
select
table2.month
,table2.salesperson_assigned
,ifnull(table1.Product1_revenue,0) as Product1_revenue
,ifnull(table2.Product2_revenue,0) as Product2_revenue
,ifnull(table1.Product1_revenue,0)+ifnull(table2.Product2_revenue,0) as total_revenue
from table2
left outer join table1
on table2.salesperson_assigned=table1.salesperson_assigned and table1.month=table2.month
order by 2,1;
返回:
Month salesperson_assigned Product1_revenue Product2_revenue total_revenue
1 10 100 100 200
2 10 200 200 400
1 11 40 0 40
2 11 800 0 800
3 11 400 0 400
1 12 0 40 40
2 12 0 200 200
ps:请考虑发布代码以重现您的数据,以便您获得更快的响应。