【发布时间】:2017-03-20 08:08:43
【问题描述】:
+-----+---------+--------+---------+
| PID | account | amount | balance |
+-----+---------+--------+---------+
| 1 | 1 | 100 | dr |
| 2 | 5 | 100 | cr |
| 3 | 2 | 30 | dr |
| 4 | 1 | 30 | cr |
| 5 | 1 | 50 | cr |
| 6 | 4 | 50 | dr |
+-----+---------+--------+---------+
我有上面的示例表,我正在使用 CI,我想选择“列金额 WHERE 列余额值为 dr”的总金额减去“列金额 WHERE 列余额值为 cr”的总金额。现在如何将其写入一个查询中??
我目前正在做的是使用 2 个查询,如下所示
// Get total amount that has balance dr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'dr');
$result = $query->result();
$total_dr = $result[0] -> amount;
// Get total amount that has balance cr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'cr');
$result = $query->result();
$total_cr = $result[0] -> amount;
// Minus total_dr to total_cr
$total = $total_dr - $total_cr;
我认为必须有一种方法可以在不查询两次的情况下获得 $total,但我在 SO 中找不到任何线索。
【问题讨论】:
标签: php mysql codeigniter