darkpoon 发表于 2018-10-3 11:56:07

mysql倒排的优化

  今天数据库负载就直线上升,数据库连接数撑爆。把语句抓出来一看,罪魁祸首是一条很简单的语句:SELECT * FROM eload_promotion_code WHERE 1 AND exp_time  先看一下这个表的索引:
  >show index from eload_promotion_code\G
  *************************** 1. row ***************************
  Table: eload_promotion_code
  Non_unique: 0
  Key_name: PRIMARY
  Seq_in_index: 1

  Column_name:>  Collation: A
  Cardinality: 921642
  Sub_part: NULL
  Packed: NULL
  Null:
  Index_type: BTREE
  Comment:
  Index_comment:
  *************************** 2. row ***************************
  Table: eload_promotion_code
  Non_unique: 1

  Key_name:>  Seq_in_index: 1
  Column_name: cishu
  Collation: A
  Cardinality: 15
  Sub_part: NULL
  Packed: NULL
  Null:
  Index_type: BTREE
  Comment:
  Index_comment:
  *************************** 3. row ***************************
  Table: eload_promotion_code
  Non_unique: 1

  Key_name:>  Seq_in_index: 2
  Column_name: exp_time
  Collation: A
  Cardinality: 921642
  Sub_part: NULL
  Packed: NULL
  Null:
  Index_type: BTREE
  Comment:
  Index_comment:
  可以看到id为主键,idx_cishu_exp为(cishu,exp_time)的唯一索引
  看一下这个语句的执行计划,可以看到排序没有用到索引

  explain SELECT * FROM eload_promotion_code WHERE 1 AND exp_time  *************************** 1. row ***************************
  id: 1
  select_type: SIMPLE
  table: eload_promotion_code
  type: ref

  possible_keys:>
  key:>  key_len: 4
  ref: const
  rows: 460854
  Extra: Using where; Using filesort
  1 row in set (0.00 sec)

  将select * 换成select>
  >explain select>  *************************** 1. row ***************************
  id: 1
  select_type: SIMPLE
  table: eload_promotion_code
  type: range

  possible_keys:>
  key:>  key_len: 8
  ref: NULL
  rows: 460862
  Extra: Using where; Using index; Using filesort
  1 row in set (0.00 sec)

  好吧,这个语句有救了,采用延时关联先取出id,然后根据id获取原表所需要的行,改写后的语句来了:select * from eload_promotion_code inner join (select>  执行一下,0.3s出结果。
  这样就算完了。

页: [1]
查看完整版本: mysql倒排的优化