【发布时间】:2020-08-15 09:24:13
【问题描述】:
我有 3 个 MYSQL 表 User 表和 2 个 Transactions 表。
我的用户表如下。
id inviter_id active .... (other columns)
2 1 1
3 1 1
4 2 1
5 1 1
6 2 1
我的 txn1 表是
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 表是
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 的利润,它应该获取用户 4 和用户 6 在 txn1 和 txn2 表中的 txns。
到目前为止,我尝试过的是,
$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;
这个查询的问题是我得到了一个巨大的总和值。
【问题讨论】:
-
'它应该得到用户 4 和用户 6 在 txn1 和 txn2 表中的 txns。这些表中没有名为 user 的列 - 您需要澄清这些表之间的关系并添加所需的输出
标签: php mysql codeigniter