谈下最近开发中用了一下Mysql的set字段类型
set类型简介
最近项目中使用了set类型去定义一个常量集合字段,为了深入了解该类型用法去官方文档学习了一下并进行了一些用法的尝试。
set是可以具有0到64个值的字符串对象类型(可当集合使用),set列中的值都必须在定义时指定的值列表中选取。set中的每个字符串成员值之间用逗号(,)分隔,所以成员值中不能包含逗号字符串(所以可把set类型列看成通过逗号将成员拼接成完整字符串的列)。
注意事项与剖析操作
操作案例表:
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字段根据定义顺序分配数字存储值并维护一个上下文用于检索与排序,如以上例中定义顺序字符串值与数字映射所生成的上下文如下:

可通过select collection,collection+0 from dictionary查看上表中存储set字段collection存储字符串对应的十进制数字值,如存储字符串为’a,c’,则十进制为3(1+2),Mysql检索时会根据数字值3转换为对应的字符串再进行返回。用例:
- 查找set列中不含’e’、'b’的数据:select * from dictionary where collection < 16
- 查找含’a’成员含以下两种方式:
1.select * from dictionary where collection&1
2.select * from dictionary where find_in_collection('a',collection)

精准查找collection列为’a,d’的数据:select * where collection=9(1+)

执行数据插入:insert into dictionary (collection) value ('a,b,c,d');
再进行数据查询,会发现该数据值对应的行结果为:a,c,d,b
select * from dictionary where collection like '%,c,%'
相关推荐
-
第18问:MySQL CPU 高了,怎么办?2025-02-24 10:27:18
-
mysql索引类型 normal, unique, full text
mysql索引类型 normal, unique, full text2025-02-24 10:05:05 -
uwsgi+django+nginx 搭建部分总结2025-02-24 10:03:33
-
使用Docker配置Nginx环境部署Nextcloud2025-02-24 10:02:03
-
Nginx安装和怎么使用2025-02-24 10:00:45