从另一个表中按平均排序选择结果

时间:2011-06-20 20:52:23

标签: mysqli sql-order-by ranking

获得主要产品列表:

| id | name | content |
  1    bla     .....
  2    ble     .....
  3    blo     .....
  4    blu     .....

评分产品表:

| id | productid | score |
  1        4         4
  2        2         3
  3        4         1
  4        3         1
  3        1         1
  3        2         2

开始为产品列表编写代码,使用paginate类> smarty的

$stmt = $mysqli->prepare("SELECT id,name,content FROM products LIMIT ?,?"))
$stmt->bind_param('ii', SmartyPaginate::getCurrentIndex('id'), SmartyPaginate::getLimit('id'));
$stmt->bind_result($id, $name, $content);
$stmt->execute();

$count = '0';

while ($stmt->fetch())
 {
$array['id'][]          = $id;
$array['name'][]        = $name;
$array['content'][] = $content;
$count++;
  }

rest code...

它对于产品列表非常有效,但现在我需要根据得分表中的平均值来订购产品。

我已经看过许多排名的例子,但仍然无法构建任何可行的例子。

提前致谢 骆驼

1 个答案:

答案 0 :(得分:1)

从产品左连接中选择*(选择avg(得分)avgscore,产品来自productid得分组)s.sproductid = product.productid order by avgscore limit 0,10

优化查询的一种方法是将产品表中的平均值存储起来并偶尔更新。

相关问题