Reputation: 3738
So I have this sql code in Drupal:
$query = db_query('SELECT wpv.nid, n.title, AVG(vote) average FROM {wp_votes} wpv
LEFT JOIN {node} n on wpv.nid = n.nid
GROUP BY wpv.nid
ORDER BY average DESC
LIMIT 3');
It works just fine, but I need to write it with db_select:
$query2 = db_select('wp_votes','wpv');
$query2->join('node','n','wpv.nid = n.nid');
$query2->fields('wpv',array('nid','vote'));
$query2->fields('n',array('title'));
$rez = $query2->execute()->fetchAll();
My problem is that I don't know how I can get the average vote(votes are 1,2 or 3). How do i rewrite the part with AVG(vote). I tried with addEXpression('AVG(vote)') but it didn't work as expected, I got the average for all the entries, not just for those with the same id.
Thanks.
Upvotes: 2
Views: 2066
Reputation: 676
For AVG you need to use addExpression() and groupBy and you will have something like this
<?php
$query2 = db_select('wp_votes','wpv');
$query2->join('node','n','wpv.nid = n.nid');
$query2->fields('wpv',array('nid','vote'));
$query2->fields('n',array('title'));
$alias = $query2->addExpression('AVG(vote)', 'average');
$query2->groupBy('wpv.nid');
$query2->sortBy($alias, 'DESC');
$rez = $query2->execute()->fetchAll();
I'm not sure about sorting by $alias, but theoretical, it should work.
Upvotes: 2
Reputation: 71
Seems that you forgot to use
$query->groupBy('wpv.nid');
that's why you got the AVG for all records.
Upvotes: 2