mysql5.7 生成列 generated column用法实例分析
本文实例讲述了mysql5.7生成列generatedcolumn用法。分享给大家供大家参考,具体如下:
生成列的值是根据列定义中的表达式计算得出的。
mysql5.7支持两种类型的生成列:
1、virtual生成列:当从表中读取记录时,才计算该列值。不会把数据持久化在硬盘上。
2、stored生成列:向表中写入记录时,计算该列值,并作为常规列持久化存储在硬盘上。
所以virtual相较于stored需要的的存储空间更少,如果未指定生成列类型,mysql5.7默认生成列类型为virtual。
定义生成列的语法:
col_namedata_type[GENERATEDALWAYS]AS(expression) [VIRTUAL|STORED][NOTNULL|NULL] [UNIQUE[KEY]][[PRIMARY]KEY] [COMMENT'string']
我们创建一个表,指定其中一个字段为生成列。
CREATETABLEtest( idINT(11)UNSIGNEDNOTNULLAUTO_INCREMENT, chineseDOUBLENOTNULLDEFAULT'0', mathDOUBLENOTNULLDEFAULT'0', englishDOUBLENOTNULLDEFAULT'0', total_scoreDOUBLEAS(chinese+math+english), PRIMARYKEY(id) )ENGINE=INNODBDEFAULTCHARSET=utf8mb4;
我们向表中插入一条数据
insertintotest(chinese,math,english)values(66,72,54);
select*fromtest;
注意,生成的列不允许我们人为的指定值,这会引发ERROR3105的错误。
如果要在insert语句中包含total_score字段名,则只能将其值设为DEFAULT
insertintotest(chinese,math,english,total_score)values(33,44,55,DEFAULT);
如果表已经存在了,我们可以通过altertable语句来创建,修改,删除生成列。
altertabletestaddcolumntimes_scoredoublegeneratedalways as(chinese*math*english)stored;
修改生成列的数据类型和表达式
altertabletestmodifycolumntimes_scorefloatgeneratedalways as(chinese*math*english*10)stored;
重命名生成的列
altertabletestchangetimes_scoretimes_score_newfloatgeneratedalways as(chinese*math*english*10)stored;
删除生成的列
altertabletestdropcolumntimes_score_new;
virtual列不能更改为stored的生成列,反之亦然。只能先删除,然后再重新添加
altertabletestdropcolumntotal_score; altertabletestaddcolumntotal_scoredoublegeneratedalways as(chinese+math+english)stored;
表中的常规字段,可以修改为stored生成列,但不能是virtual生成列
altertabletestmodifycolumnchinesedoublegeneratedalways as(math+1)stored;
stored生成列可以修改为常规字段,值为生成值
altertabletestmodifycolumntotal_scoredouble;
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL常用函数大汇总》、《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》及《MySQL数据库锁相关技巧汇总》
希望本文所述对大家MySQL数据库计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。