如何使用 where 条件连接三个 tables 以获得两个关系 table 的总和,以便更快地查询 1M 数据

How to join three tables with where condition to get sum of two relational table's amount for 1M data faster query

我有3个table:super_consumers、balance_ins、充值

super_consumers table:

id            name
----------    ----
1              A
2              B

balance_ins table:

id    super_consumer_id  amount   type(1,2)
---   -----------------  ------   ----
1            1             10       1
2            1             20       1
3            2             10       2

充值table:

id    super_consumer_id  amount  status(0,1)
---   -----------------  ------  ------
1            1             5       1
2            1             10      1
3            2             15      0

我想得到每个super_consumerstable的总余额金额总充值金额通过以下一些条件,

  1. Total_balance_in 金额来自 balance_in table 其中类型 == 1
  2. Total_recharge 充值金额 table 其中状态 == 1

预期结果:

[
    'id' = 1,
    'name' = 'A',
    'total_balance_in' = 30,
    'total_recharge' = 15
],
[
    'id' = 2,
    'name' = 'B',
    'total_balance_in' = 0,
    'total_recharge' = 0
]

如何在 'laravel DB Query' 或 'mysql' 中正确编写此查询?

尝试:

select super_consumers.id ,
       super_consumers.name,
       IF(tot_balance_amount IS NULL, 0 , tot_balance_amount) as tot_balance_amount,
       IF(tot_recharge_amount IS NULL ,0, tot_recharge_amount) as tot_recharge_amount
from  super_consumers 
left  join (select super_consumer_id,sum(amount) as tot_balance_amount  
            from balance_ins  
            where type='1' 
            group by super_consumer_id ) as a 
on  super_consumers.id=a.super_consumer_id
left join ( select super_consumer_id,sum(amount) as tot_recharge_amount  
            from recharges  
            where `status`='1' 
            group by super_consumer_id ) as b 
on  super_consumers.id=b.super_consumer_id;

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/44

查询:

SELECT
    c.id
,   c.name
,   ifNull(sum(res.balance), 0) as balance_sum
,   ifNull(sum(res.recharge), 0) as recharge_sum
FROM
    super_consumers as c
    LEFT JOIN 
    (
      SELECT
        b.super_consumer_id
      , b.amount as balance
      , 0 as recharge
      FROM
        balance_ins as b
      WHERE
        b.type = 1

      UNION

      SELECT
        r.super_consumer_id
      , 0 as balance
      , r.amount as recharge
      FROM
        recharges as r
      WHERE
        r.status = 1
    ) as res
    ON
        c.id = res.super_consumer_id
GROUP BY
    c.id
,   c.name

结果:

id name balance_sum recharge_sum
1 A 30 15
2 B 0 0