代码之家  ›  专栏  ›  技术社区  ›  TerminatorX

MySQL数据库所需金额

  •  0
  • TerminatorX  · 技术社区  · 6 年前

    我希望您能帮助我解决以下问题:
    我有以下两张表:

    tableA

    table

    表A。currencyA始终等于表B中相关项目的currencyB。
    我需要返回以下结果:

    enter image description here

    基本上,在结果中,我需要返回表a中的所有项目+表B中项目的摘要。我一直在尝试几个问题,但似乎我无法用一句话来回答这个问题。我尝试过的方法没有返回item4的数据(请注意,item4在tableB中没有条目)。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Samir Selia    6 年前

    对你需要的东西有一点干净的方法

    SELECT z.*,
    (z.totalA - z.in) AS difference
    FROM (
        SELECT a.idA, a.currencyA, a.totalA,
        IF(b.idB IS NOT NULL, SUM(b.amountA), 0) AS `in`
        FROM tableA a
        LEFT JOIN tableB b ON a.idA = b.idA
        GROUP BY a.idA
    ) z;
    

    输出

    idA currencyA   totalA  in  difference
    1      usd       1000   550   450
    2      usd       2000   700   1300
    3      eur       3000   600   2400
    4      usd       4000    0    4000
    

    Working Demo

        2
  •  0
  •   TerminatorX    6 年前

    我相信这样的方法可以奏效:

    select 
        tableA.idA, 
        tableA.currencyA as currency, 
        tableA.totalA as total, 
        case when (sum(tableB.amountB) is null) then 0 else sum(tableB.amountB) end as 'in',
        case when (sum(tableB.amountB) is null) then tableA.totalA else 
        tableA.totalA-sum(tableB.amountB) end as 'difference'
    from 
        tableA left outer join tableB on tableA.idA=tableB.idA
    group by tableA.idA;