当前位置:网站首页>[learning] database: MySQL query conditions have functions that lead to index failure. Establish functional indexes

[learning] database: MySQL query conditions have functions that lead to index failure. Establish functional indexes

2022-07-05 06:20:00 Daidou family

Preface

  • We all know mysql When where When there is a function query in the condition , Can cause indexes to fail
  • for example :
select * from test where DATE(swap_time) = DATE( date_sub( CURRENT_DATE, INTERVAL 1 DAY ) );
  • use Explain Commands can be viewed sql Implementation plan of , Whether the index is used , Can pass possible_keys and rows It's easy to see
  • In this case mysql 5.7 There are different solution suggestions before and after the version
  • First, query the current mysql The version used
select VERSION();

mysql 5.7 Previous version optimization suggestions

select * from test where swap_time >= CURRENT_DATE and swap_time < date_add(CURRENT_DATE,INTERVAL 1 day);

mysql 5.7 Optimization suggestions for future versions

  • stay 5.7 Later versions of the database support the establishment of functional indexes
  • Create virtual columns
alter table test add column swap_time_index datetime GENERATED ALWAYS AS (DATE(swap_time));
  • Re execution sql
select * from test where DATE(swap_time) = DATE( date_sub( CURRENT_DATE, INTERVAL 1 DAY ) );
  • I found that the query speed has become faster
  • utilize Explain View execution plan
Explain select * from test where DATE(swap_time) = DATE( date_sub( CURRENT_DATE, INTERVAL 1 DAY ) );
  • It is found that the functional index is used

Reference address :

mysql Build functional index
MySQL Explain Detailed explanation
MySQL Functional index and optimization
mysql How to view sql Statement execution time and efficiency

原网站

版权声明
本文为[Daidou family]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140615147822.html