0

I have two tables. (Below given are example tables. originally I have 6 tables)

Table cpp;

----------------------
| name    |  spent1  |
----------------------
|john     |   32     |
|Johny    |   2      |
----------------------

Table java

----------------------
| name    |  spent2  |
----------------------
|mary     |   42     |
|Johny    |   2      |
----------------------

Output what I want is like

---------------------------------
| name    |  spent1  |  spent2  |
---------------------------------
|john     |   32     |  null    |
|Johny    |   2      |  2       |
|mary     |   null   |  42      |
---------------------------------

I tried many things and couldn't get the answer. Can someone suggest me a join in mysql to get the desired output.

Pawan
  • 423
  • 6
  • 28

2 Answers2

0

You could achieve that by a union of two queries

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

Note that by just specifying UNION with ALL - the duplicate entry for johny is automatically removed.

PaulF
  • 6,673
  • 2
  • 18
  • 29
0

Without redesigning the schema (probably your best option) you could create a temporary table & query that - the following should easily be extended to six tables :

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;
PaulF
  • 6,673
  • 2
  • 18
  • 29