mysql快速检测字段值是否包含大写的精简指南
核心方法速查
方法1:正则表达式(推荐)
-- 检测任意位置包含大写 select * from table where column regexp binary '[a-z]';
注意:可能存在不兼容字符集utf8mb4_bin问题 可用rlike替换
select * from table where column rlike '[a-z]'; -- 检测全大写(排除数字符号) select * from table where column regexp binary '^[a-z]+$';
替换语句:
select * from table where column rlike '^[a-z]+$';
方法2:二进制对比
-- 检测首字母大写(这种的识别不出首字母是数字的数据) select * from table where binary left(column,1) = upper(left(column,1)); -- ascii码检测(a-z=65-90)(下面的n代表第几位是大写) select * from table where ord(substring(column,n,1)) between 65 and 90;
方法3:强制校验规则
-- 查询时指定区分大小写(精确查询 把column字段的字符集设置成utf8mb4_bin ,会区分大小写 ) select * from table where column collate utf8mb4_bin = 'targetvalue';
优化技巧(大数据量必备)
1.虚拟列索引(mysql 8.0+)
alter table users add column name_upper varchar(255) generated always as (upper(username)) virtual, add index idx_upper(name_upper);
2. 预处理首字母
alter table products add column initial char(1) generated always as (upper(left(code,1))) stored, add index idx_initial(initial);
性能警示
- 避免全表扫描:binary和regexp会使查询效率下降30%+
- 优先方案:对常检测字段建立预处理列+索引
- 查询技巧:结合limit 1快速判断是否存在大写
select 1 from table where column regexp binary ‘[a-z]' limit 1;
实战案例
-- 用户表检测邮箱大小写重复 select email from ( select lower(email) as lower_email, group_concat(email) as duplicates from users group by lower_email having count(*) > 1 ) t where duplicates regexp binary '[a-z]';
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论