Skip to content
Advertisement

Joining two tables with same keys but different fields

I have two tables both all with the same fields Except for one. I want to combine these two tables with the resulting table having all the fields from both including the two fields that are not the same in each table. I.e:

lets say I have table order_debit with schema

order_id, date_of_order, debit_balance

5, 2019, 100
2, 2021, 30

and table order_credit with schema

order_id, date_of_order, credit_balance

1,2020, 35
2,2021, 40

What I want is a final table with the schema

order_id, date_of_order, credit_balance, debit_balance

5, 2019, 100, 0
2, 2021, 30, 40
1, 2020, 0, 35

I cant figure out how to do the joins without getting duplicate values, I dont think there will be too many overlaps of order_ids but there will definitely be some.

Advertisement

Answer

For MySQL, you can use UNION ALL and GROUP BY

SELECT
    order_id, date_of_order, SUM(credit_balance), SUM(debit_balance)
FROM 
(
    SELECT order_id, date_of_order, 0 AS credit_balance, debit_balance FROM tbl_debit
    UNION ALL
    SELECT order_id, date_of_order, credit_balance, 0 AS debit_balance FROM tbl_credit
) FROM t
GROUP BY order_id, date_of_order
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement