參考資料:
Generated Columns in MySQL 5.7.5
MySQL 5.7新特性之Generated Column(函數(shù)索引)
Generated Column
在MySQL 5.7中,支持兩種Generated Column,即Virtual Generated Column和Stored Generated Column,前者只將Generated Column保存在數(shù)據(jù)字典中(表的元數(shù)據(jù)),并不會將這一列數(shù)據(jù)持久化到磁盤上;后者會將Generated Column持久化到磁盤上,而不是每次讀取的時候計算所得。很明顯,后者存放了可以通過已有數(shù)據(jù)計算而得的數(shù)據(jù),需要更多的磁盤空間,與Virtual Column相比并沒有優(yōu)勢,因此,MySQL 5.7中,不指定Generated Column的類型,默認(rèn)是Virtual Column。
如果需要Stored Generated Golumn的話,可能在Virtual Generated Column上建立索引更加合適
綜上,一般情況下,都使用Virtual Generated Column,這也是MySQL默認(rèn)的方式
語法:
<type> [ GENERATED ALWAYS ] AS ( <expression> ) [ VIRTUAL|STORED ]
[ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ] [ COMMENT <text> ]
應(yīng)用:
為了實現(xiàn)對json數(shù)據(jù)中部分?jǐn)?shù)據(jù)的索引查詢,可以使用MySQL5.7中的虛擬列(virtual column)功能
創(chuàng)建表
create table user(uid int auto_increment,data json,primary key(uid));
構(gòu)建數(shù)據(jù)
insert into user values (NULL,'{"name":"wang","address":"shenyang"}');insert into user values (NULL,'{"name":"zhao","address":"riben"}');
構(gòu)建姓名的虛擬列
alter table user add user_name varchar(20) generated always as (data->'$.name');
構(gòu)建索引
alter table user add index idx_name(user_name);
查詢
select * from user where user_name='"wang"';
查詢分析(explain …… \G)
可以看出用了索引了
此時的表的結(jié)構(gòu)由于多出了user_name這一虛擬列,再插入別的數(shù)據(jù)要注意在表后指明插入列(不能給虛擬列插入數(shù)據(jù))
insert into user(uid,data) values (NULL,'{"name":"pan","address":"sichuan"}');