CI在两个表中的两个不同条件上选择SUM

时间:2017-05-03 10:43:05

标签: php mysql codeigniter

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();

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

// 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
    )
);

2 个答案:

答案 0 :(得分:0)

替换此

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

用这个

$this->db->groupBy('tPID');

答案 1 :(得分:0)

SELECT SUM(IN-OUT),b.location from table1 a 
INNER JOIN table2 b on a.tPID=b.tPID
GROUP BY b.location