Thomas Clowes
Thomas Clowes

Reputation: 4609

Codeigniter select_avg('columnname') WHERE thisaverage > x

What I want to do is select items from my database where the average review is greater than 7.

$this->db->select_avg('reviews.overall');

That query selects the average review 'as overall'.

Therefore i assumed i could simply then use

$this->db->where('overall>','7');

This however does not work.

ANy ideas?

Thanks

EDIT Putting in a space

        $this->db->select_avg('reviews.overall');
    $this->db->where('overall >','7');

Yields the error

Column 'overall' in where clause is ambiguous

It is ambiguous but how am I now meant to reference it??

Thx

Upvotes: 1

Views: 2466

Answers (1)

ghostika
ghostika

Reputation: 1503

It's writen in the codeigniter user manual too:

$this->db->select_avg(); Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

If you enable profiler in CI, you would see, what query does this code generate. Your code is generated like this:

SELECT AVG(reviews.overall) as reviews.overall FROM ....

Use it like this:

$this->db->select_avg('reviews','overall');
$this->db->from('table name');
$this->db->where('overal >', 7);
$Q = $this->db->get();

Upvotes: 2

Related Questions