比较慢MySQL查询

时间:2012-07-19 22:15:40

标签: mysql

我有一个看似简单的问题,但我正在努力。我有两张桌子如下。

表1有房间事件和时间(秒) 表2有房间访问时间(秒)和人名

对于表1中的每一行,我想输出最后一个进入房间的人,但前提是他们在最后5分钟内进入房间

时间是两个表的主要索引

表1(事件)的例子

|time      |event|
|1294427839|poff |
|1294427939|pofn |
|1294428839|poff |

表2(条目)的例子

|time      |name|
|1294427829|tpeters |
|1294427929|jsmith |
|1294428829|abeach |

表1有大约5,000行,表2大约有300,000行 我目前正在使用以下查询,但需要几分钟才能完成。有人可以请求我做错了。

select (SELECT name FROM entries entries WHERE entries.time > events.time-300 and  entries.time < events.time order by entries.time desc limit 1) from events events

非常感谢任何帮助。

添加了更多详细信息:

ID  SELECT_TYPE        TABLE    TYPE    POSSIBLE_KEYS   KEY     KEY_LEN     ROWS    FILTERED    EXTRA
1   PRIMARY            events   index                   PRIMARY 8           3       100     Using index
2   DEPENDENT SUBQUERY entries  index   PRIMARY         PRIMARY 8           1       300     Using where

CREATE TABLE事件(   time int(11)NOT NULL DEFAULT&#39; 0&#39;,   主要关键(time) )ENGINE = InnoDB DEFAULT CHARSET = utf8 ROW_FORMAT = COMPACT;

CREATE TABLE条目(   time int(11)NOT NULL DEFAULT&#39; 0&#39;,   主要关键(time) )ENGINE = InnoDB DEFAULT CHARSET = utf8 ROW_FORMAT = COMPACT;

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT name, ev_time, en_time
FROM (
  SELECT
    name,
    IF(events.time = @last_time, 0, 1) AS last,
    @last_time := events.time AS ev_time,
    entries.time AS en_time
  FROM events
  LEFT JOIN entries ON (entries.time BETWEEN events.time-300 AND events.time)
  ORDER BY events.time, entries.time
) as tmp
WHERE last = 1

sqlfiddle

测试了它