Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

sql - Select average from MySQL table with LIMIT

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...