• ADADADADAD

    MySQL5.7中的函数索引怎么用[ mysql数据库 ]

    mysql数据库 时间:2024-11-26 22:11:50

    作者:文/会员上传

    简介:

    在MySQL5.7之前的版本中,函数索引是无法用到索引的,也不支持虚拟列,下边的SQL执行时候回进行全表扫描:select * from t1 where mod(mode_id,8)=1MySQL5.7支持虚拟列,并且可以使用

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    在MySQL5.7之前的版本中,函数索引是无法用到索引的,也不支持虚拟列,下边的SQL执行时候回进行全表扫描:
    select * from t1 where mod(mode_id,8)=1
    MySQL5.7支持虚拟列,并且可以使用函数索引。
    确定数据库版本:

      mysql> select version();

      +------------+

      | version() |

      +------------+

      | 5.7.18-log |

      +------------+

    查看表结构:

      mysql> show create table t_func_mod \G

      *************************** 1. row ***************************

      Table: t_func_mod

      Create Table: CREATE TABLE `t_func_mod` (

      `id` int(11) NOT NULL,

      `mod_id` int(11) GENERATED ALWAYS AS ((`id` % 8)) VIRTUAL,

      PRIMARY KEY (`id`),

      KEY `idx_mod_id` (`mod_id`)

      ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    插入测试数据:

      mysql> insert into t_func_mod values(1,default);

      Query OK, 1 row affected (0.08 sec)

      mysql> insert into t_func_mod values(2,default);

      Query OK, 1 row affected (0.06 sec)

      mysql> insert into t_func_mod values(3,default);

      Query OK, 1 row affected (0.01 sec)

      mysql> insert into t_func_mod values(4,default);

      Query OK, 1 row affected (0.01 sec)

      mysql> insert into t_func_mod values(5,default);

      Query OK, 1 row affected (0.04 sec)

      mysql> insert into t_func_mod values(6,default);

      Query OK, 1 row affected (0.00 sec)

      mysql> insert into t_func_mod values(7,default);

      Query OK, 1 row affected (0.00 sec)

      mysql> insert into t_func_mod values(8,default);

      Query OK, 1 row affected (0.00 sec)

    注意:插入数据时候,虚拟列要使用default,否则会报错。
    查看测试表数据:

      mysql> select * from t_func_mod;

      +----+--------+

      | id | mod_id |

      +----+--------+

      | 8 | 0 |

      | 1 | 1 |

      | 2 | 2 |

      | 3 | 3 |

      | 4 | 4 |

      | 5 | 5 |

      | 6 | 6 |

      | 7 | 7 |

      +----+--------+

    通过explain查看执行计划,已经使用到了索引:

      mysql> explain select * from t_func_mod where mod_id=5;

      ----+-------------+------------+------------+------+---------------+------------+---------+-------+------+----------+-------------+

      | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

      +----+-------------+------------+------------+------+---------------+------------+---------+-------+------+----------+-------------+

      | 1 | SIMPLE | t_func_mod | NULL | ref | idx_mod_id | idx_mod_id | 5 | const | 1 | 100.00 | Using index |

    MySQL5.7中的函数索引怎么用.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: mysql5.7