简体   繁体   中英

How do I fix this MySQL query?

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM