我想学习CodeIgniter,下面是一个例子:
我有一个数据库(tbl_points(
我有一个这样的输出:
id | sku | 点|
---|---|---|
1 | 001 | 10 |
2 | 001 | <1>|
3 | 002 | 5 |
4 | 002 | -2 |
5 | 001 | <1>
如果您想为ci3编写查询。
$this->db->select('sku');
$this->db->select_sum('point');
$this->db->from('tbl_points');
$this->db->group_by('sku');
$query = $this->db->get();
$row = $query->result();
print_r($row);
这是用一个简单的mysql SUM((解决的,请参阅聚合函数描述
select * , sum(`point`) as my_point
from `tbl_points`
group by `sku`
以防你真的需要一个新的";id";,您可以使用用户定义变量扩展查询,为每一新行添加+1:
set @row_num=0;
select * , sum(`point`) as my_point, @row_num:=@row_num+1 AS new_id
from `tbl_points`
group by `sku`
检查相应的mysql fiddle
使用Codeigniter查询生成器创建该查询CI3.x:的示例
$this->db->select('* , sum(point) as my_point');
$this->db->group_by('sku');
$query = $this->db->get('tbl_points');
对于用户定义变量,您需要2个查询,类似于:
$sql="set @row_num:=0";
$this->db->query($sql);
$sql="select * , sum(`point`) as my_point, @row_num:=@row_num+1 AS new_id
from `tbl_points`
group by `sku`
";
$query=$this->db->query($sql);
要快速输出结果,您可以写下以下行:
echo '<pre>';print_r($query->result());
无论如何,建议检查如何生成CI查询结果
您需要先对其求和,然后按以下字段分组:-
$sql = "select id,sku, sum(`point`) as my_point from `tbl_points`
group by `sku`";
$query = $this->db->query($sql);
输出结果:-
echo '<pre>';
print_r($query->result());
您的输出结果:-
id sku my_point
1 001 8
3 002 3