0

我有以下查询需要时间。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"
4

2 回答 2

0

我相当确定您的主键不是聚集键(它可能为空或不唯一,或者您曾在某一时刻更改过它),因为这可以解释这种行为,至少如果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) ...
于 2016-04-26T16:17:10.227 回答
0
  1. 确保您在 MyTable.transaction_Id 上有一个索引
  2. 确保在 MySQL 配置中将innodb_buffer_pool_size设置为合适的值
于 2016-04-26T15:10:45.493 回答