MySQL 5.6快速定位不合理索引

# 若CARDINALITY / TABLE_ROWS小于10%(经验值),那么表示数据重复率较高,通常需要考虑是否有必要创建该索引

#########################################################
# MySQL 5.6
目前5.6的STATISTICS表中关于Cardinality的统计是错误的!!!具体可见MySQL bugs #78066
但是,表innodb_index_stats中关于Cardinality值得统计依然是正确的
 
#########################################################
SELECT 
     t.TABLE_SCHEMA,
     t.TABLE_NAME,INDEX_NAME,
     s.CARDINALITY, 
     t.TABLE_ROWS, 
     s.CARDINALITY/t.TABLE_ROWS AS SELECTIVITY
FROM
    information_schema.TABLES t,
    (SELECT database_name,table_name,index_name,stat_value AS CARDINALITY
     FROM mysql.innodb_index_stats 
     WHERE (database_name,table_name,index_name,stat_name) IN 
           (SELECT table_schema,table_name,index_name,CONCAT('n_diff_pfx0',MAX(seq_in_index))
              FROM information_schema.STATISTICS
          -- where table_name='xxxxx' 
          GROUP BY table_schema , table_name , index_name )) s
WHERE t.table_schema = s.database_name 
  AND t.table_name = s.table_name 
  AND t.table_rows != 0
  AND t.table_schema NOT IN ( 'mysql','performance_schema','information_schema') 
ORDER BY SELECTIVITY;

以下部分出自:
#############################################################
# mysql 5.7  表STATISTICS记录了各个索引的CARDINALITY值
#############################################################

SELECT 
     t.TABLE_SCHEMA,t.TABLE_NAME,INDEX_NAME, CARDINALITY, 
    TABLE_ROWS, CARDINALITY/TABLE_ROWS AS SELECTIVITY
FROM
    information_schema.TABLES t,
 (
  SELECT table_schema,table_name,index_name,cardinality
  FROM information_schema.STATISTICS 
  WHERE (table_schema,table_name,index_name,seq_in_index) IN (
  SELECT table_schema,table_name,index_name,MAX(seq_in_index)
  FROM information_schema.STATISTICS
  GROUP BY table_schema , table_name , index_name )
 ) s
WHERE
    t.table_schema = s.table_schema 
        AND t.table_name = s.table_name AND t.table_rows != 0
        AND t.table_schema NOT IN ( 'mysql','performance_schema','information_schema') 
ORDER BY SELECTIVITY;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/8587afaf1225f786ba3f8a033587619c.html