tags:

views:

166

answers:

2
SELECT 
  avg(con_hits) as avg_hits 
FROM 
  content 
WHERE 
  con_type = 1 
  AND con_posttime < $twelve_hrs_ago 
  AND con_refresh = 0 
ORDER BY 
  con_posttime DESC 
LIMIT 100

I would like it to go to the first record that was posted at least 12 hours ago (denoted by the $twelve_hrs_ago variable which has the suitable timestamp), and take the average of the con_hits column, for the next 100 records. In my example, it disregards the LIMIT, and takes the average of every record in the table.

Is there a way to bypass that?

+12  A: 

LIMIT is applied to the resultset, after AVG is calculated. You can do what you want, with a subselect:

SELECT avg(con_hits) as avg_hits
FROM (
  SELECT con_hits
  FROM content
  WHERE
    con_type = 1
    AND con_posttime < $twelve_hrs_ago
    AND con_refresh = 0
  ORDER BY con_posttime DESC
  LIMIT 100
) x;

You can use the database to calculate the time offset too. Replace $twelve_hrs_ago above with:

date_add(now(), interval -12 hour)
troelskn
Perfect! In your 2nd suggestion, using the code you provided results in avg_hits being NULL.And whats the point of that x in the end?
Yegor
In my opinion. It would be more readable to use date_sub instead. The function name denotes the purpose.
J.J.
The x at the end is required because you must give a correlation name (i.e. a table alias) to any derived query in the FROM clause.
Bill Karwin
With the optional "AS" keyword the purpose becomes more clear: "SELECT avg(x.Foo) FROM (SELECT Foo FROM Table) AS x"
Tomalak
@J.J.: DATE_SUB() is MySQL centric, whereas DATE_ADD() should work everywhere.
Tomalak
@Yegor: I assumed that `con_posttime` is a datetime type; Maybe you used something else (Such as a timestamp)? In that case, you have to convert appropriately.
troelskn
its indeed a timestamp
Yegor
hm .. I just tested, and a timestamp works. Maybe your database server's clock is out of sync?
troelskn
+1  A: 

What about:


SELECT avg(con_hits) as avg_hits FROM (
    SELECT con_hits FROM content 
    WHERE con_type = 1 AND con_posttime < $twelve_hrs_ago AND con_refresh = 0
    ORDER BY con_posttime DESC
    LIMIT 100
    ) 

Mysql supports subqueries, so this might do it for you.

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

Rob