优化最大值查询

时间:2015-08-02 04:46:36

标签: sql postgresql optimization time statistics

我想就如何优化查询提出建议?我希望能让它运行得更快,因为我认为它会以速度消耗UX。

我的程序每小时收集一次数据,我想优化我的查询,该查询获取最新数据并为特定事件创建前100名人员,

SELECT a.user_id as user, nickname, value, s.created_on 
FROM stats s,accounts a 
WHERE a.user_id = s.user_id AND event_id = 1 AND s.created_on in  
(SELECT created_on FROM stats WHERE created_on >= NOW() - '1 hour'::INTERVAL) 
ORDER BY value desc 
LIMIT 100

我的查询从event_id = 1的最后一小时返回前100名,但我希望优化它,我相信子查询是问题的根本原因。我已尝试过其他查询,但最终会出现重复或结果不是来自最新数据集

谢谢

EDIT ::

表帐户包含[user_id,昵称]

stats表包含[user_id,event_id,value,created_on]

1 个答案:

答案 0 :(得分:0)

NOW() - '1 hour'::INTERVAL不是MySQL语法;也许你的意思是NOW() - INTERVAL 1 HOUR

IN ( SELECT ... )优化得很差。

不知道accountsstats(1:1,1:很多等)之间的关系,我只能猜测可能有用的东西:

SELECT  a.user_id as user, nickname, value, s.created_on
    FROM  stats s,accounts a
    WHERE  a.user_id = s.user_id
      AND  event_id = 1
      AND  s.created_on >= NOW() - INTERVAL 1 HOUR)
    ORDER BY  value desc
    LIMIT  100
INDEX(event_id, value) -- if they are both in `a`
INDEX(user_id, created_on)

...或

SELECT  user_id as user, nickname, value,
        ( SELECT MAX(created_on) FROM stats
                WHERE  user_id = a.user_id )  AS created_on
    FROM  accounts
      AND  event_id = 1
      AND  EXISTS 
      ( SELECT  *
            FROM  stats
            WHERE  created_on >= NOW() - INTERVAL 1 HOUR 
              AND  user_id = a.user_id
      )
    ORDER BY  value desc
    LIMIT  100 
INDEX(user_id, created_on)
INDEX(event_id, value)

请提供

    每个表
  • SHOW CREATE TABLE
  • EXPLAIN SELECT ...;任何合理的候选人