使用此查询
SELECT
o1.created,
SEC_TO_TIME(TIMESTAMPDIFF(second, o1.created, (SELECT MAX(created) FROM orders o2 WHERE o2.created < o1.created and o2.created >= '2012-06-01'))) tsd
FROM
orders o1
WHERE o1.created >= '2012-06-01'
ORDER BY tsd DESC LIMIT 100
我想知道,如果有任何重要时间没有订单,这个时间跨度有多长。
以下是解释:
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: o1
type: range
possible_keys: created
key: created
key_len: 4
ref: NULL
rows: 2649278
Extra: Using where; Using index; Using filesort
*************************** 2. row ***************************
id: 2
select_type: DEPENDENT SUBQUERY
table: o2
type: range
possible_keys: created
key: created
key_len: 4
ref: NULL
rows: 2649278
Extra: Using where; Using index
created
的类型为timestamp
。
查询现在运行了一个多小时。更改架构中的任何内容都不是一种选择。这是一次性查询,但我只是好奇是否可以提升性能。
答案 0 :(得分:1)
尝试使用此查询。它更快吗?
select created,Previous_created,
IF(tsd<>0,SEC_TO_TIME(tsd),0) as diff
from
(
select created,
IF(@prev<>0,TIMESTAMPDIFF(second, @prev,created),0) tsd,
@prev Previous_created,
@prev:=created f2
from orders,(select @prev:=0) t1
WHERE created >= '2012-06-01'
order by created
) t2
order by tsd desc limit 100
答案 1 :(得分:0)
我尝试使用没有子查询的解决方案:
select o1.created, TIMESTAMPDIFF(second, o1.created, o3.created) tsd
from orders o1
inner join orders o2 on o2.created < o1.created and o2.created >= '2012-06-01'
left join orders o3 on o3.created > o2.created
where o1.created >= '2012-06-01' and o3.id is null;
如果created
列被编入索引,可能要快得多。我担心diff列的排序不能在mysql中编入索引。