我有 2 个表,我想合并它们,使它们提供基于月的数据。像这样:
表1:
month | data1 | data2
--------|-------|------
6 | 1 | 1
5 | 1 | 1
4 | 1 | 2
2 | 1 | 2
1 | 1 | 3
表2:
month | data3
--------|------
7 | 1
6 | 1
4 | 1
3 | 1
1 | 2
=> tableResult:
month | data1 | data2 | data3
--------|-------|-------|-------
7 | 0 | 0 | 1
6 | 1 | 1 | 1
5 | 1 | 1 | 0
4 | 1 | 2 | 1
3 | 0 | 0 | 1
2 | 1 | 2 | 0
1 | 1 | 3 | 2
是否可以在sql query
中获得 tableresult ?
或唯一的选择是查询每个表,然后用php处理它?
顺便说一句, table1 和 table2 都是重要的视图
答案 0 :(得分:1)
使用联接和联合
select t1.month,data1,data1,t2.data3
from table1 t1 left join table2 t2 on t1.month=t2.month
union
select t2.month,t1.data1,t1.date2,t2.data3
from table1 t1 right join table2 t2 on t1.month=t2.month
答案 1 :(得分:1)
您正在寻找full join
:
select coalesce(t1.month, t2.month) as month,
coalesce(t1.data1, 0) as data1,
coalesce(t1.data2, 0) as data2,
coalesce(t2.data3, 0) as data3
from t1 full join
t2
on t1.month = t2.month;