前言
-
索引(index) 在SQL中可以大大提高 查询效率。
-
SQL索引列中,如果使用了运算和函数,索引将无法生效。
-
如果索引列的数据量大且稳定,可以使用 生成列 来固定对索引列的计算和函数运算,并对该生成列添加索引提高查询效率。
如何创建生成列
官网原文:https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html
CREATE TABLE
支持生成列的规范。根据列定义中包含的表达式计算生成列的值。
NDB从MySQL NDB Cluster 7.5.3开始,存储引擎 支持生成列 。
举例:
通过sidea和sideb列中直角三角形的边的长度 ,并计算下斜边的长度 sidec(其他边的平方和的平方根):
CREATE TABLE triangle (
sidea DOUBLE,
sideb DOUBLE,
sidec DOUBLE AS (SQRT(sidea * sidea + sideb * sideb))
);
INSERT INTO triangle (sidea, sideb) VALUES(1,1),(3,4),(6,8);
从表中选择将产生以下结果:
mysql> SELECT * FROM triangle;
+-------+-------+--------------------+
| sidea | sideb | sidec |
+-------+-------+--------------------+
| 1 | 1 | 1.4142135623730951 |
| 3 | 4