简体   繁体   中英

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

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?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM