find_in_set 是 mysql 的一个字符串处理函数,用于在逗号分隔的字符串列表中查找指定值的位置。
一、函数语法
find_in_set(str, strlist)
| 参数 | 说明 |
|---|---|
| str | 要查找的字符串 |
| strlist | 逗号分隔的字符串列表(如 'a,b,c') |
返回值:
- 如果找到,返回 位置(从 1 开始)
- 如果没找到,返回 0
- 如果 str 或 strlist 为 null,返回 null
二、基本示例
select find_in_set('b', 'a,b,c,d'); -- 返回 2
select find_in_set('z', 'a,b,c,d'); -- 返回 0
select find_in_set(null, 'a,b,c,d'); -- 返回 null
select find_in_set('b', null); -- 返回 null
select find_in_set('b', ''); -- 返回 0三、常见使用场景
1. 判断某个值是否在逗号分隔的字符串中
-- 查询所属系统包含 '1' 的记录
select * from vehicle
where find_in_set('1', belonging_system) > 0;2. 按逗号分隔字符串排序
-- 按用户指定的顺序排序(如 3,1,2) select * from user order by find_in_set(id, '3,1,2');
3. 结合 coalesce 处理 null
-- 如果参数为 null,查询全部;否则按 in 匹配 select * from vehicle where (?1 is null or find_in_set(?1, belonging_system) > 0);
4. 统计某个值出现的次数
-- 统计 vin 中包含 'l58' 的记录数
select count(*) from vehicle
where find_in_set('l58', vin) > 0;四、在你的场景中使用 find_in_set
场景:belonging_system 是逗号分隔的字符串
-- 查询 belonging_system 包含 systemid 的所有记录
select * from vehicle
where find_in_set('1', belonging_system) > 0;
-- 结合参数判空
select * from vehicle
where (?1 is null or find_in_set(?1, belonging_system) > 0);jpa 原生查询写法
@query(value = "select * from vehicle v " +
"where (coalesce(?1, null) is null or find_in_set(?1, v.belonging_system) > 0)",
nativequery = true)
page<vehicle> findbysystemid(@param("systemid") string systemid, pageable pageable);五、find_in_set vs in
| 对比项 | find_in_set | in |
|---|---|---|
| 适用场景 | 字段是逗号分隔的字符串 | 字段是单个值 |
| 用法 | find_in_set('a', column) > 0 | column in ('a', 'b') |
| 索引使用 | ❌ 无法使用索引 | ✅ 可以使用索引 |
| 性能 | 全表扫描,数据量大时慢 | 有索引时快 |
| 参数传递 | 传单个字符串 | 需要传多个值(集合) |
核心区别:
- in 用于多个值的列表匹配
- find_in_set 用于单个字段中存储的逗号分隔字符串匹配
六、性能注意事项
⚠️ find_in_set 无法使用索引,在数据量大时性能较差。
| 数据量 | 性能表现 |
|---|---|
| < 1 万条 | ✅ 可以接受 |
| 1 万 ~ 10 万 | ⚠️ 可能变慢 |
| > 10 万 | ❌ 严重性能问题 |
优化建议
改用关联表(推荐)
- 将
belonging_system从逗号分隔字符串改为多对多关联表 - 使用
in或exists查询,利用索引
- 将
使用 json 数组(mysql 5.7+)
-- 存储为 json 数组 select * from vehicle where json_contains(belonging_system, '"1"');
使用全文索引
alter table vehicle add fulltext(belonging_system); select * from vehicle where match(belonging_system) against('1');
七、完整示例
-- 1. 基本查找
select find_in_set('2', '1,2,3,4'); -- 返回 2
-- 2. 在 where 中使用
select * from user where find_in_set('admin', roles) > 0;
-- 3. 结合 order by(按指定顺序)
select * from product
where id in (3,1,2)
order by find_in_set(id, '3,1,2');
-- 4. 结合 case
select
name,
case
when find_in_set('admin', roles) > 0 then '管理员'
when find_in_set('user', roles) > 0 then '普通用户'
else '未知'
end as role_name
from user;八、总结
| 要点 | 说明 |
|---|---|
| 功能 | 在逗号分隔的字符串中查找值的位置 |
| 返回值 | 找到返回位置(1-based),没找到返回 0 |
| 主要场景 | 判断值是否存在于逗号分隔字段中 |
| 优点 | 简单直观,适合小数据量 |
| 缺点 | 无法使用索引,大数据量时性能差 |
| 替代方案 | 关联表、json 数组、全文索引 |
建议:如果 belonging_system 经常被查询,建议改为多对多关联表,彻底解决性能问题。如果数据量小(< 1 万),find_in_set 可以接受。
到此这篇关于mysql中find_in_set函数的具体使用的文章就介绍到这了,更多相关mysql find_in_set内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论