+-----+---------+--------+---------+
| 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 '減去'列金額的總金額WH列的金額有價值cr'。現在我怎麼把這個寫入一個查詢?mysql如何用2分不同,其中的條件在1個查詢
什麼我目前做的是使用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;
我認爲必須有一種方式來獲得$總在不查詢兩次,但這樣我找不到任何鉛。
你先生太棒了。非常感謝您提供非常簡單高效的查詢。 – Charas