MYSQL 从多个 table 中获取利润数据时出现问题

MYSQL Issue in fetching profit data from multiple table

我有 3 个 MYSQL 表 User table 和 2 个 Transactions table.

我的用户table如下

id     inviter_id    active .... (other columns)
2      1             1
3      1             1
4      2             1
5      1             1
6      2             1

我的 txn1 table 是

id     payer_id     receiver_id     amount     type
1      2            1               20         profit
2      3            1               30         profit
3      4            2               20         profit
4      3            2               50         profit
5      5            2               20         profit

我的 txn2 table 是

id     payer_id     receiver_id     amount     txn_type
1      2            1               20         profit
2      3            2               30         profit
3      4            2               20         profit
4      3            1               50         profit
5      5            1               20         profit

我需要得到的是, 假设我正在查询用户 2。我需要他使用 inviter_id 列从他的每个下线或推荐中获得的利润。

例如,如果我想从Txn1和Txn2中获取用户#2的利润table,则应该获取用户4和用户6在txn1和txn2中的交易table s.

到目前为止我尝试过的是,

$userID = 2;
$this->db->select('u.id as partner_id, SUM(txn1_profit.amount) AS t1Profit, SUM(txn2_profit.amount) AS t2Profit');
$this->db->from('users u');
$this->db->join('txn1 txn1_profit', "u.id = txn1_profit.payer_id AND $userID = txn1_profit.receiver_id AND 'profit' = txn1_profit.txn_type",'LEFT');
$this->db->join('txn2 txn2_profit', "u.id = txn2_profit.payer_id AND $userID = txn2_profit.receiver_id AND 'profit' = txn2_profit.txn_type",'LEFT');
        
        $this->db->where('u.inviter_id', $userID);      
        $this->db->group_by('u.id');

        $query = $this->db->get(); 
        $row = $query->result();
        
        if (empty($row))
            return FALSE;
        return $row;

这个查询的问题是我得到了一个巨大的总和值。

如果您的交易模式 tables 相同,那么我建议您更改您的模式并使用一个交易 table 来存储此类信息。通过更改您当前的设计将帮助您构建简单的查询,可能会减少 no。连接数。

对于您当前的模式,我可以想到 2 种可能的方法来解决您的利润值问题。

根据您在 sub-clause 中的交易 table 计算总和,然后与用户 table

进行联合
select u.inviter_id, 
       sum(t1.t1Profit), 
       sum(t2.t2Profit),
       sum(t1.t1Profit) + sum(t2.t2Profit) total
from users u
left join (
  select payer_id, sum(amount) t1Profit
  from tx1
  where 2 = receiver_id 
  and 'profit' = type
  group by payer_id
) t1 on u.id = t1.payer_id
left join (
  select payer_id, sum(amount) t2Profit
  from tx2
  where 2 = receiver_id 
  and 'profit' = txn_type
  group by payer_id
) t2  on u.id = t2.payer_id
where u.inviter_id = 2;

或者使用 union all 合并您的交易 table 的数据,然后与用户 table

进行联合
select u.inviter_id, 
       sum(t1.amount) total
from users u
left join (
  select payer_id, amount
  from tx1
  where 2 = receiver_id 
  and 'profit' = type
  union all 
  select payer_id, amount
  from tx2
  where 2 = receiver_id 
  and 'profit' = txn_type
) t1 on u.id = t1.payer_id
where u.inviter_id = 2;

DEMO