简体   繁体   中英

Mysql innodb query returning slow result

I have following query which is taking time. Mytable type is innodb and have primary key on field tsh_id I have also added index on transaction_Id field

following is implementation inside my database stored procedure.

 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;

Please suggest any sort of improvement

Edit:

Explain to query says

"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"
  1. Make sure you have an index on MyTable.transaction_Id
  2. Make sure you have the innodb_buffer_pool_size set to a decent value in your MySQL config

I am fairly certain your primary key is not a clustered key (its might be null or not unique or you changed it at one point), because that would explain this behaviour, at least if transaction_Id isn't unique either (and otherwise you wouldn't need limit 1 ).

To improve this specific query, you can create the following index:

create index ix_mytable_transaction_id_tsh_id on MyTable (transaction_id, tsh_id desc);

Use explain again.

If it doesn't use the new key, force it:

SELECT ... FROM  `MyTable` force index(ix_mytable_transaction_id_tsh_id) ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM