我有以下查询,这需要时间。 Mytable类型是innodb,在字段tsh_id上有主键 我还在transaction_Id字段
上添加了索引以下是我的数据库存储过程中的实现。
DECLARE lv_timestamp DATETIME(3);
SET @lv_timestamp = NOW(3);
IF(mycondition) then
SET @lv_Duration :=( SELECT UNIX_TIMESTAMP (@lv_timestamp) - UNIX_TIMESTAMP ( `changedon` )
FROM `MyTable`
WHERE transaction_Id = _transaction_Id
ORDER BY tsh_id DESC
LIMIT 1)
End if;
请提出任何改进建议
编辑:
向查询说明
"select_type":"SIMPLE",
"table":"MyTable",
"type":"ref",
"possible_keys":"IX_MyTable_Transaction",
"key":"IX_MyTable_Transaction",
"key_len":"98",
"ref":"const",
"rows":1,
"Extra":"Using where"
答案 0 :(得分:0)
答案 1 :(得分:0)
我相当确定你的主键不是聚簇键(它可能是null或不唯一,或者你在某一时刻改变它),因为这可以解释这种行为,至少如果transaction_Id
不是唯一的(否则你不需要limit 1
)。
要改进此特定查询,您可以创建以下索引:
create index ix_mytable_transaction_id_tsh_id on MyTable (transaction_id, tsh_id desc);
再次使用explain
。
如果它不使用新密钥,请强制它:
SELECT ... FROM `MyTable` force index(ix_mytable_transaction_id_tsh_id) ...