【发布时间】:2013-08-07 17:58:05
【问题描述】:
我想在约 5m 行的表中查找所有具有后继的每小时记录。
我试过了:
SELECT DISTINCT (date_time)
FROM my_table
JOIN (SELECT DISTINCT (DATE_ADD( date_time, INTERVAL 1 HOUR)) date_offset
FROM my_table) offset_dates
ON date_time = date_offset
和
SELECT DISTINCT(date_time)
FROM my_table
WHERE date_time IN (SELECT DISTINCT(DATE_ADD(date_time, INTERVAL 1 HOUR))
FROM my_table)
第一个在几秒钟内完成,秒挂几个小时。 我可以理解越早越好,但为什么会有如此巨大的性能差距?
-------- 编辑 ---------------
这是两个查询的EXPLAIN
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 1710 Using temporary
1 PRIMARY my_table ref PRIMARY PRIMARY 8 offset_dates.date_offset 555 Using index
2 DERIVED my_table index NULL PRIMARY 13 NULL 5644204 Using index; Using temporary
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY my_table range NULL PRIMARY 8 NULL 9244 Using where; Using index for group-by
2 DEPENDENT SUBQUERY my_table index NULL PRIMARY 13 NULL 5129983 Using where; Using index; Using temporary
【问题讨论】:
-
我可能错了,但是子查询很重。因此,如果您使用
JOIN和ON子句执行它,它会更快,因为它不会检索子选择的每个结果。在第二个查询中,您首先检索子选择的所有结果,然后查看它。
标签: mysql