MySQL. How to combine or match specifics rows from two tables

45 views Asked by At

First, the title is not very clear. With this example I would like to know if there is a solution with SQL code or if it has to be worked in the other side with C#, Java, PHP, etc.

The principle is this:

  1. There is a table of Inputs, like this:
    ID  Name   Amount
    1   AA     10   
    2   BB     9
    3   CC     8
    4   DD     1
    5   ZZ     2
  1. And there is a table of Outputs:
    ID  Name   Fouls   
    1   BB     4
    2   ZZ     1
  1. What I'm trying to get is a subtraction of the quantities, based on each matching column, hoping to get the following:
    Name   Diff
    AA     10   
    BB     5
    CC     8
    DD     1
    ZZ     1

Can it be done directly with SQL?

2

There are 2 answers

2
GMB On BEST ANSWER

You can left join:

select i.name, i.amount - coalesce(o.fouls, 0) diff
from inputs i
left join outputs o on o.name = i.name
1
Gordon Linoff On

I think you just want a left join and arithmetic:

select i.id, i.name, i.amount - coalesce(o.fouls, 0)
from inputs i left join
     outputs o
     using (id)