赞
踩
最近项目中使用了set类型去定义一个常量集合字段,为了深入了解该类型用法去官方文档学习了一下并进行了一些用法的尝试。
set是可以具有0到64个值的字符串对象类型(可当集合使用),set列中的值都必须在定义时指定的值列表中选取。set中的每个字符串成员值之间用逗号(,)分隔,所以成员值中不能包含逗号(,)字符串(实质即Mysql把成员值通过逗号拼接成一个完整的字符串)。
操作案例表:
create table dictionary
(
id int auto_increment primary key,
collection set('a', 'c', 'f', 'd', 'e', 'b') not null
);
create index dictionary_collection_index on dictionary (collection);
set集合类型有以下细节需要注意:
当插入成员值重复(如"a,a")时则set列最后结果只有一个(“a”),如果设置严格SQL模式则会报错
成员值中尾随的空格会被删除(“a, b”->“a,b”)
mysql将set字段根据定义顺序分配二进制数字存储值并维护一个上下文用于检索与排序,如以上例中定义顺序字符串值与数字映射所生成的上下文如下:
成员 | 十进制值(collection+0) | 二进制值 |
---|---|---|
a | 1 | 0001 |
c | 2 | 0010 |
f | 4 | 0100 |
d | 8 | 1000 |
e | 16 | 10000 |
b | 32 | 100000 |
可通过select collection,collection+0 from dictionary
查看上表中存储set字段collection存储字符串对应的十进制数字值,如存储字符串为’a,c’,则十进制为3(1+2),Mysql检索式会根据数字值3转换为对应的字符串再进行返回。用例:
select * from dictionary where collection < 16
select * from dictionary where collection&1
select * from dictionary where find_in_collection('a',collection)
select * where collection=9
插入值时mysql会将值根据set成员的定义顺序进行成员值重排序,如:
执行数据插入:insert into dictionary (collection) value ('a,b,c,d');
再进行数据查询,会发现该数据值对应的行结果为:a,c,d,b
由于set类型也是一个字符串,所以可以通过like
检索,如查找collection列含’c’成员的数据行:select * from dictionary where collection like '%,c,%'
本文主要参考自Mysql官方文档:https://dev.mysql.com/doc/refman/8.0/en/set.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。