I have the following query:
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
The query gets the greatest datelast value and subtracts it from the greatest datestart value for every ID (which is the length of a user session), and th开发者_开发知识库en averages it.
The outer most query is there only to average the resulting times. Is there any way to optimize this query?
Output from 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
Is the first SELECT really necessary ?
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
)
I can't test now and I think it would work too. Otherwise, your query looks good.
You can optimize the query by adding a (datelast, product_id) key (always put the most restrictive field first, to increase selectivity).
精彩评论