從MySQL 5.7開始,支持兩種Generated Column该贾,即Virtual Generated Column和Stored Generated Column;
區(qū)別
- Virtual Generated Column保存在數(shù)據(jù)字典中(表的元數(shù)據(jù))尊勿,并不會將這一列數(shù)據(jù)持久化到磁盤上汞舱;
- Stored Generated Column持久化到磁盤上蚁阳,而不是每次讀取的時候計算所得
創(chuàng)建語法
CREATE TABLE t1 (c1 INT);
ALTER TABLE t1 ADD COLUMN c2 INT GENERATED ALWAYS AS (c1 + 1) STORED;
CREATE TABLE t1 (c1 INT, c2 INT GENERATED ALWAYS AS (c1 + 1) STORED);
使用限制:
1稠茂、主鍵索引不能包含virtual generated column 如:
mysql> create table t(a int, b int , c int as (a / b), primary key(c));
ERROR 3106 (HY000): 'Defining a virtual generated column as primary key' is not supported for generated columns.
2、Virtual Generated Column不能作為外鍵
3次哈、不能使用非確定函數(shù)胎署,如:
mysql> alter table a ADD p3 DATE GENERATED ALWAYS AS (curtime()) virtual;
ERROR 3763 (HY000): Expression of generated column 'p3' contains a disallowed function: curtime.
4、無法刪除源列窑滞,如:
mysql> alter table t100w drop k1;
ERROR 3108 (HY000): Column 'k1' has a generated column dependency.
5琼牧、非法數(shù)據(jù),如:
mysql> create table t( x int, y int, z int as( x / 0));
Query OK, 0 rows affected (0.22 sec)
mysql> insert into t(x,y) values(1,1);
ERROR 1365 (22012): Division by 0
測試100w表并發(fā)50執(zhí)行100次全表掃描DB性能表現(xiàn)
測試sql:
SELECT test_vv FROM t100w limit 10000; #虛擬列無索引
虛擬列函數(shù):
(concat(k1
,_utf8mb4'-',k2
))
stored類型
-
執(zhí)行耗時
stored類型-耗時 -
CPU負載
stored類型-cpu負載 -
qps
stored類型-qps
virtual 類型
說明
- 以上測試表結果集較小葛假,且虛擬列計算函數(shù)計算較為簡單障陶。可以大致參考比較出Virtual Generated Column會有一定的CPU開銷(函數(shù)列需要計算結果集)聊训。
- 對于不是很核心的業(yè)務,函數(shù)模型不復雜的恢氯,復雜低頻業(yè)務建議使用Virtual Generated Column带斑。
- 添加Stored Generated Column列不是online操作,代價較大且需要額外的存儲成本勋拟。