本文介绍了使用LIMIT从MySQL表中选择平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取价格最低的5件商品的平均值,并按其所附的用户名分组.但是,以下查询给出了每个用户的平均价格(当然是价格),但我只想返回一个答案.

I am trying to get the average of the lowest 5 priced items, grouped by the username attached to them. However, the below query gives the average price for each user (which of course is the price), but I just want one answer returned.

SELECT AVG(price) 
  FROM table 
 WHERE price > '0' && item_id = '$id' 
GROUP BY username 
ORDER BY price ASC 
   LIMIT 5

推荐答案

我想这就是您要追求的目标:

I think this is what you're after:

SELECT AVG(items.price)
  FROM (SELECT t.price
          FROM TABLE t
         WHERE t.price > '0' 
           AND t.item_id = '$id'
      ORDER BY t.price
         LIMIT 5) items

它将返回5个最低价格的平均值-一个答案.

It will return the average of the 5 lowest prices - a single answer.

这篇关于使用LIMIT从MySQL表中选择平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 21:02