0

I Have two table:
Table 1 name: Buy

Name  | Name code | Number |

  a           01         25
  a           01         25
  b           02         75
  c           03         100
  c           03         25
And table 2 name: Sell

Name  | Name code | Number |

  b           02         60
  b           02         40
  c           03         80
  c           03         40
  d           04         45
  d           04         50

So, how to make two tables join like this (Using MYSQL Query):

Name  | Name code | Number | Name | Name code | Number |

  a           01         50 (SUM)   NULL     NULL       NULL
  b           02         75         b         02       100(SUM)
  c           03         125(SUM)    c         03       120(SUM)
  NULL       NULL        NULL       d         04         90(SUM)
When i type (SUM), it mean that value is SUM with 2 rows
Because this is so hard for me, so i need help so much
Please help me, i don't know how to do that. Thanks so much
And also if i need condition like b < 70 or C < 30 etc...

Jacky Euro
  • 69
  • 1
  • 8
  • `SELECT table1.name, table1."name code", sum(table1.number) AS number, table2.name, table2."name code", sum(table2.number) AS number FROM table1 LEFT JOIN table2 ON table1.name = table2.name GROUP BY table1.name, table2.name` Or something along these lines, I just wrote it blindly. – kry Aug 10 '18 at 09:33
  • Actually, cancel that, that will clear the null rows. You need the full outer join instead: https://stackoverflow.com/questions/4796872/how-to-do-a-full-outer-join-in-mysql – kry Aug 10 '18 at 09:36

2 Answers2

0

It's a bit awkward because MySQL does not support full outer joins. EDIT because of bug:

SELECT B.name, B.name_code, B.total, S.name, S.name_code, S.total
FROM (
  SELECT name, name_code, SUM(number) AS total FROM buy GROUP BY name, name_code
) B LEFT JOIN (
  SELECT name, name_code, SUM(number) AS total FROM sell GROUP BY name, name_code
) S ON B.name = S.name
UNION
SELECT NULL, NULL, NULL, name, name_code, SUM(number) AS total FROM sell
WHERE name NOT IN (SELECT name FROM buy)
GROUP BY name, name_code;
Amadan
  • 191,408
  • 23
  • 240
  • 301
0
SELECT table_1.Name,table_1.Namecode ,SUM(table_1.Number),table_2.Name,

table_2.Namecode,SUM(table_2.Number)

FROM table_1 

FULL OUTER JOIN table_2

ON table_1.name = table_2.name

GROUP BY table_1.name,table_2.name
Sheril Dev
  • 173
  • 1
  • 1
  • 7