Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

avg() returns odd result 1

Status
Not open for further replies.

Microbe

Programmer
Oct 16, 2000
607
AU
Hey folks,

I have never used avg() before and am puzzled by the result I am getting.

SQL code

Code:
SELECT * FROM s12345 ORDER BY id DESC LIMIT 5

plus php code
Code:
do{
  echo $row_trend["id"] . " = " . $row_trend["height"]. "<br>";
 }while($row_trend = mysql_fetch_assoc($trend));

gives me the expected rows as follows

68 = 0.30
67 = 0.30
66 = 0.30
65 = 0.30
64 = 0.32

However, the SQL
Code:
SELECT avg(height) as avg FROM s12345 ORDER BY id DESC LIMIT 5

plus PHP

Code:
echo "<div>The average of the 5 readings is " . $row_trend["avg"];

gives me

"The average of the 5 readings is 0.332941"

The actual average is .304 What am I doing wrong?

Steve
- I have fun with telemarketers
 
Make a derived table (alias drtble, say) then average over it. Like this.
[tt]
SELECT avg(drtbl.height) as avg FROM (SELECT height FROM s12345 ORDER BY id DESC LIMIT 5) AS drtbl;
[/tt]
(I qualify there drtble.height with alias drtble for clarity, it works too without.)
 
microbe, the AVG() function is processed on the entire table before the LIMIT is applied to the results -- thus, there is only one row being returned

note that some versions of mysql won't let you do LIMIT in a subquery

if you're dealing with only 5 rows, i would simply do the average in php

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
I wonder if members could run the sql I posted on different mysql versions they possess to see how it would or not be working (err message). It certain works on mine.

Whether avg() is evaluated before the "from subquery", I would only deduce something from the documentation on "Restriction on Subqueries" (D.3) on a different sort of "from subqueries".
quote
... Subqueries in the FROM clause cannot be correlated subqueries. They are materialized (executed to produce a result set) before evaluating the outer query, ...
unquote
So I might deduce without acquiring the support of source code that avg() is evaluated _after_ the derived table is made and the LIMIT consummed. I could be wrong.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top