generated columns

1.generated columns:可以定义一个带有函数表达的列

例1:

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>show create table triangle\G

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

       Table: triangle

Create Table: CREATE TABLE `triangle` (

  `sidea` double DEFAULT NULL,

  `sideb` double DEFAULT NULL,

  `sidec` double GENERATED ALWAYS AS (sqrt(((`sidea` * `sidea`) + (`sideb` * `sideb`)))) VIRTUAL

) ENGINE=InnoDB DEFAULT CHARSET=utf8


2.generated columns参数

virtual:没有存储列的值,不占存储空间,在5.7.8之前,虚拟列不支持索引,到5.7.8,Innodb引擎开始支持secondary  indexse,不指定参数,默认是虚拟列,如例1;


stored:列真实存在,并需要存储空间,支持索引;


例2:

mysql>create table t3(c1 int,c2 int generated always as (c1+1) virtual,c3 int generated always as (c1+1) stored);   


mysql>insert into t3(c1) values(1);


mysql>select * from t3;

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

| c1   | c2   | c3   |

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

|    1 |    2 |    2 |

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


添加索引:

mysql>alter table t3 add index index_c2(c2);

mysql>alter table t3 add index index_c3(c3);


查看表的状态信息:

mysql>show table status like 't3'\G

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

           Name: t3

         Engine: InnoDB

        Version: 10

     Row_format: Dynamic

           Rows: 1

 Avg_row_length: 16384

    Data_length: 16384

Max_data_length: 0

   Index_length: 0

      Data_free: 0

 Auto_increment: NULL

    Create_time: 2016-12-22 22:45:38

    Update_time: 2016-12-22 22:40:49

     Check_time: NULL

      Collation: utf8_general_ci

       Checksum: NULL

 Create_options:

        Comment:


查看执行计划:


mysql>desc select * from t3 where c2=2\G   

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

           id: 1

  select_type: SIMPLE

        table: t3

   partitions: NULL

         type: ref

possible_keys: index_c2

          key: index_c2

      key_len: 5

          ref: const

         rows: 1

     filtered: 100.00

        Extra: NULL

1 row in set, 1 warning (0.00 sec)



mysql>explain select * from t3 where c2=2\G

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

           id: 1

  select_type: SIMPLE

        table: t3

   partitions: NULL

         type: ref

possible_keys: index_c2

          key: index_c2

      key_len: 5

          ref: const

         rows: 1

     filtered: 100.00

        Extra: NULL

1 row in set, 1 warning (0.00 sec)


也可以在虚拟列上再创建虚拟列:


mysql>alter table t3 add c4 int generated always as (c2+1) virtual;


mysql>alter table t3 drop c4;


上一篇:GTID的复制的搭建过程


下一篇:判断GTID复制中主从是否同步脚本