我有两张桌子。 (下面给出的是示例表。最初我有6个表)
表cpp;
----------------------
| name | spent1 |
----------------------
|john | 32 |
|Johny | 2 |
----------------------
表java
----------------------
| name | spent2 |
----------------------
|mary | 42 |
|Johny | 2 |
----------------------
输出我想要的东西就像
---------------------------------
| name | spent1 | spent2 |
---------------------------------
|john | 32 | null |
|Johny | 2 | 2 |
|mary | null | 42 |
---------------------------------
我尝试了很多东西而无法得到答案。有人可以建议我加入mysql以获得所需的输出。
答案 0 :(得分:0)
你可以通过两个查询联合实现这一目标
select Table1.name as name , Table1.spent as spent1 , Table2.spent as spent2 from Table1
Left JOIN Table2 on Table1.name = Table2.name
union
select Table2.name as name , Table1.spent as spent1 , Table2.spent as spent2 from Table2
Left JOIN Table1 on Table1.name = Table2.name
ORDER BY name
请注意,只需将UNION指定为ALL,就会自动删除johny的重复条目。
答案 1 :(得分:0)
如果不重新设计架构(可能是您最好的选择),您可以创建一个临时表&查询 - 以下内容应该很容易扩展到六个表:
drop temporary table if exists temp;
create temporary table temp ENGINE=MEMORY as (select * from
(select name, spent1, null as spent2, null as spent3, .... from Table1
union
select name, null, spent2, null, .... from Table2
union
select name, null, null, spent3, .... from Table3
.....
) a);
select name, sum(spent1), sum(spent2), sum(spent3), ....
from temp
group by name;