mysql5.7 生成列 generated column用法实例分析

吾爱主题 阅读:153 2024-04-05 16:20:32 评论:0

本文实例讲述了mysql5.7 生成列 generated column用法。分享给大家供大家参考,具体如下:

生成列的值是根据列定义中的表达式计算得出的。

mysql5.7支持两种类型的生成列:

1、virtual 生成列:当从表中读取记录时,才计算该列值。不会把数据持久化在硬盘上。

2、stored 生成列:向表中写入记录时,计算该列值,并作为常规列持久化存储在硬盘上。

所以 virtual 相较于 stored 需要的的存储空间更少,如果未指定生成列类型,mysql5.7 默认生成列类型为 virtual。

定义生成列的语法:

?
1 2 3 4 col_name data_type [generated always] as (expression)   [virtual | stored] [ not null | null ]   [ unique [ key ]] [[ primary ] key ]   [comment 'string' ]

我们创建一个表,指定其中一个字段为生成列。

?
1 2 3 4 5 6 7 8 create table test (   id int (11) unsigned not null auto_increment,   chinese double not null default '0' ,   math double not null default '0' ,   english double not null default '0' ,   total_score double as (chinese + math + english),   primary key (id) ) engine=innodb default charset=utf8mb4;

我们向表中插入一条数据

?
1 insert into test(chinese, math, english) values (66, 72, 54);
?
1 select * from test;

注意,生成的列不允许我们人为的指定值,这会引发error 3105的错误。

如果要在 insert 语句中包含 total_score 字段名,则只能将其值设为 default

?
1 insert into test(chinese, math, english, total_score) values (33, 44, 55, default );

如果表已经存在了,我们可以通过alter table语句来创建,修改,删除生成列。

?
1 2 alter table test add column times_score double generated always as (chinese * math * english) stored;

修改生成列的数据类型和表达式

?
1 2 alter table test modify column times_score float generated always as (chinese * math * english * 10) stored;

重命名生成的列

?
1 2 alter table test change times_score times_score_new float generated always as (chinese * math * english * 10) stored;

删除生成的列

?
1 alter table test drop column times_score_new;

virtual 列不能更改为 stored 的生成列,反之亦然。只能先删除,然后再重新添加

?
1 2 3 alter table test drop column total_score; alter table test add column total_score double generated always as (chinese + math + english) stored;

表中的常规字段,可以修改为 stored 生成列,但不能是 virtual 生成列

?
1 2 alter table test modify column chinese double generated always as (math + 1) stored;

stored 生成列可以修改为常规字段,值为生成值

?
1 alter table test modify column total_score double ;

希望本文所述对大家MySQL数据库计有所帮助。

原文链接:https://www.cnblogs.com/jkko123/p/10176722.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容