0

有了这个查询

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

查询现在运行了一个多小时。更改架构中的任何内容都不是一种选择。这是一次性查询,但我只是好奇是否可以提高性能。

4

2 回答 2

1

尝试使用此查询。它更快吗?

SQLFiddle 演示

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
于 2012-12-13T13:39:35.300 回答
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如果列被索引,它可能会快很多。恐怕无法在 mysql 中索引 diff 列的排序。

于 2012-12-13T13:14:33.820 回答