Php CI选择两个表中两个不同条件下的总和

Php CI选择两个表中两个不同条件下的总和,php,mysql,codeigniter,Php,Mysql,Codeigniter,我上面有这两个表,现在我想在一次查询中根据表1中的位置查询表2中每个产品的输入和输出的总和。我希望我的结果按乘积分组,所以为了求和,我想根据位置得到每个乘积的输入和输出 Table 1 +------+----------+ | tPID | location | +------+----------+ | 1 | 1 | | 2 | 2 | +------+----------+ Table 2 +-------+------+---------+--

我上面有这两个表,现在我想在一次查询中根据表1中的位置查询表2中每个产品的输入和输出的总和。我希望我的结果按乘积分组,所以为了求和,我想根据位置得到每个乘积的输入和输出

Table 1
+------+----------+
| tPID | location |
+------+----------+
|    1 |       1  |
|    2 |       2  |
+------+----------+

Table 2
+-------+------+---------+-----+-----+
| tdPID | tPID | Product |  IN | OUT |
+-------+------+---------+-----+-----+
|     1 |    1 |     1   |   8 |   0 |
|     2 |    1 |     2   |   5 |   0 |
|     3 |    2 |     3   |   0 |   3 |
|     4 |    2 |     2   |   0 |   2 |
+-------+------+---------+-----+-----+

// My query so far, this only return total of in - out in location 1, how do i get the sum in location 2 as a result together ?
$this->db->select(SUM(IN - OUT) as total_1);
$this->db->join('table1 b', 'a.tPID = b.tPID');
$this->db->where('b.location', '1');
$this->db->group_by('b.product');
$query = $this->db->get('table2 a');
$result = $query->result();
替换这个

// Expected result
array(
    array(
        [product] => 1
        [total_at_location_1] = 8
        [total_at_location_2] = 0
    ),
    array(
        [product] => 2
        [total_at_location_1] = 5
        [total_at_location_2] = -2
    ),
    array(
        [product] => 3
        [total_at_location_1] = 0
        [total_at_location_2] = -3
    )
);
用这个

$this->db->where('b.location', '1');

看,谢谢,忘了提一下,顺便说一句,我希望我的结果按产品分组。所以总结一下,我想要的是每个地点每种产品的总进出量
$this->db->groupBy('tPID');
SELECT SUM(IN-OUT),b.location from table1 a 
INNER JOIN table2 b on a.tPID=b.tPID
GROUP BY b.location