非常慢选择/加入查询表自己

时间:2013-08-14 14:11:23

标签: mysql

新手mysql问题。

我有一个表格,其索引看起来像这样;

    "Table" "Non_unique"    "Key_name"  "Seq_in_index"  "Column_name"   "Collation" "Cardinality"   "Sub_part"  "Packed"    "Null"  "Index_type"    "Comment"   "Index_comment"
============================================================================================
    "00005" "0" "PRIMARY"   "1" "RECORD_ID" "A" "1735423"   ""  ""  ""  "BTREE" ""  ""

如果我尝试运行以下查询

SELECT
        Record_ID as rid,
        Price, 
        Price_CHANGE_Ticks,
    /* Subselect returns only one Price_change_in_ticks from the next Record_ID which may not be in sequence */
    (SELECT Price_CHANGE_Ticks FROM 00005 WHERE Record_ID > rid ORDER BY Record_ID ASC LIMIT 1) AS next_change_ticks
       FROM 00005 order by rid
       ;

它运行得很慢,解释似乎表明主要选择没有可能的键,这似乎很奇怪

"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
==============================================================================================
"1" "PRIMARY"   "00005" "index" ""  "PRIMARY"   "4" ""  "1735423"   ""
"2" "DEPENDENT SUBQUERY"    "00005" "index" "PRIMARY"   "PRIMARY"   "4" ""  "1" "Using where"

或者假设所有记录都是连续的,我尝试了这个连接,但它也非常慢;

Select pcur.record_ID from 00005 pcur LEFT JOIN 00005 plast ON (pcur.Record_ID = plast.Record_ID + 1);

任何人都可以解释这是如何以及为什么这么慢,因为据我所知,record_ID是主键,所有这一切应该基于此,所以它应该非常快?

1 个答案:

答案 0 :(得分:2)

没有可能的密钥,因为您没有任何WHERE条件。

由于依赖子查询,它运行缓慢,虽然在这种情况下很快,但仍然必须为结果中的每个记录(整个表)运行。在MySQL中,与连接相比,子查询的速度非常慢。