active record summation in codeigniter

2019-02-19 15:22发布

问题:

I want to find sum of votes and am using codeigniter and mysql. In my votes table i've a column which shows type of vote 0 for down vote and 1 for up vote how can i generate an sql that looks like this

SELECT sum(type) FROM `votes` WHERE questions_id=1

using codeigniter database class

Cheers

回答1:

That should do the trick:

$this->db->select('SUM(type) as score');
$this->db->where('question_id',1);
$q=$this->db->get('votes');
$row=$q->row();
$score=$row->score

Your $score variable now contains the sum of the types for that particular question.

Hope that helps!