Mysql优化查询:尝试获取子查询的平均值

Mysql优化查询:尝试获取子查询的平均值,mysql,optimization,subquery,aggregate-functions,average,Mysql,Optimization,Subquery,Aggregate Functions,Average,我有以下疑问: SELECT AVG(time) FROM (SELECT UNIX_TIMESTAMP(max(datelast)) - UNIX_TIMESTAMP(min(datestart)) AS time FROM table WHERE id IN (SELECT DISTINCT id FROM table WHERE product_id = 12394 AND datelast > '2

我有以下疑问:

SELECT AVG(time) FROM 
(SELECT UNIX_TIMESTAMP(max(datelast)) - UNIX_TIMESTAMP(min(datestart)) AS time
    FROM table
    WHERE id IN 
        (SELECT DISTINCT id
            FROM table
            WHERE product_id = 12394 AND datelast > '2011-04-13 00:26:59'
        )
GROUP BY id
)
as T
查询获取最大的datelast值,并从每个ID的最大datestart值(即用户会话的长度)中减去该值,然后对其进行平均

最外层的查询仅用于平均结果时间。有没有办法优化这个查询

EXPLAIN的输出:

id  select_type         table       type            possible_keys           key     key_len ref     rows    extra
1   PRIMARY             <derived2>  ALL             NULL                    NULL    NULL    NULL    7   
2   DERIVED             table       index           NULL                    id      16      NULL    26      Using where
3   DEPENDENT SUBQUERY  table       index_subquery  id,product_id,datelast  id      12      func    2       Using index; Using where
id选择类型表类型可能的键长度参考行额外
1主所有空7
2使用where的派生表索引NULL id 16 NULL 26
3依赖子查询表索引\子查询id、产品\ id、最后日期id 12 func 2使用索引;在哪里使用

第一次选择真的必要吗

SELECT
  AVG(time)
FROM 
(
  SELECT
    UNIX_TIMESTAMP(max(datelast)) - UNIX_TIMESTAMP(min(datestart)) AS time
  FROM
    table
  WHERE
    product_id = 12394 AND datelast > '2011-04-13 00:26:59'
  GROUP BY
    id
)
我现在不能测试,我想它也可以。否则,您的查询看起来不错


您可以通过添加(datelast,product_id)键(始终将最严格的字段放在第一位,以增加选择性)来优化查询。

您的问题缺少信息,例如索引内容、解释选择输出内容等。我对其进行了测试,结果确实有所不同,因为在您的版本中,max(datelast)受最后日期>'2011-04-13 00:26:59'条款的限制。有没有办法绕过这个问题?我只需要一个datelast值来匹配子句,而不是所有的行。您的意思是使用上一个查询时有max(datelast)<'2011-04-13 00:26:59'吗?这很奇怪,因为您选择的ID中datelast>'2011-04-13 00:26:59',所以max(datelast)应该始终大于'2011-04-13 00:26:59'。无论如何,正如我告诉过你的,我真的认为你的第一个查询是正确的,你可以用一个新的索引来提高性能。