时间:2021-07-01 10:21:17 帮助过:7人阅读
生成列中的值,是根据生成列的定义计算出来的!
生成列的定义如下:
col_name data_type [GENERATED ALWAYS] AS (expression) [VIRTUAL | STORED] [NOT NULL | NULL] [UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT ‘string‘]
#AS表达式表示生成列并用于计算生成列的表达式。As之前的GENERATED ALWAYS可以让生成列的性质更明确(应该没什么作用,反正是可以省略的)!
#VIRTUAL | STORED 关键字表示列值的存储方式
VIRTUAL: 不存储列值,但在读取值之前立即计算此列的数值,虚拟列不占存储空间,innodb支持虚拟列上的二级索引。为默认的存储方式。
生成列的表达式必须遵循以下的规则,否则会报错:
AUTO_INCREMENT
列不能用作在生成的列定义的基柱(An AUTO_INCREMENT
column cannot be used as a base column in a generated column definition.)CREATE TABLE
语句将以错误终止并拒绝DDL操作生成列的作用(可能不太准确):
如下一个含有json类型字段的表:
CREATE TABLE json_test ( id INT auto_increment PRIMARY KEY, userinfo json ); #插入数据 INSERT INTO json_test(userinfo) VALUES(‘{"name":"libai","address":"china","email":"libai@163.com"}‘); INSERT INTO json_test(userinfo) VALUES(‘{"name":"obama","address":"miguo","email":"libai@gmail.com"}‘); INSERT INTO json_test(userinfo) VALUES(‘{"name":"putin","address":"russia","email":"putin@gmail.com"}‘); #
给表中添加生成列
alter table json_test add column user_name varchar(40) generated always as (userinfo->"$.name") virtual; #查看表中的数据 mysql> select * from json_test; +----+--------------------------------------------------------------------+-----------+ | id | userinfo | user_name | +----+--------------------------------------------------------------------+-----------+ | 1 | {"name": "libai", "email": "libai@163.com", "address": "china"} | "libai" | | 2 | {"name": "obama", "email": "libai@gmail.com", "address": "miguo"} | "obama" | | 3 | {"name": "putin", "email": "putin@gmail.com", "address": "russia"} | "putin" | +----+--------------------------------------------------------------------+-----------+ 3 rows in set (0.00 sec) #在表中插入数据user_name列的数值会自动计算,这时候,我们就可以对user_name列添加索引!
mysql中生成列与JSON类型的索引
标签:fun 用户 lte nbsp china varchar string 添加 调用