简体   繁体   English

MySQL。 如何组合或匹配两个表中的特定行

[英]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.通过这个例子,我想知道是否有 SQL 代码的解决方案,或者它是否必须在 C#、Java、PHP 等的另一端工作。

The principle is this:原理是这样的:

  1. There is a table of Inputs , like this:有一个Inputs表,如下所示:
    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?可以直接用SQL来完成吗?

You can left join :你可以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:我认为你只想要一个left join和算术:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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