洛雪音乐源配置完全指南:从入门到精通
2026/1/22 1:47:27
FIND_IN_SET(str, strlist)函数的作用是:在strlist(逗号分隔的字符串)中查找str的位置,返回值是数字(找到则返回位置,从1开始;没找到返回0)。
结合 MyBatis 的#{ids}是为了安全地传入参数,避免 SQL 注入。
假设你有一张user表,想通过多个用户 ID(如 1,3,5)查询对应的用户信息,就可以用这个函数。
<!-- UserMapper.xml --><selectid="selectUserByIds"resultType="com.example.entity.User">SELECT * FROM user WHERE FIND_IN_SET(id, #{ids})</select>// UserMapper.javaimportorg.apache.ibatis.annotations.Param;importjava.util.List;importcom.example.entity.User;publicinterfaceUserMapper{// 注意:参数名要和 XML 中的 #{ids} 对应,建议用 @Param 显式指定List<User>selectUserByIds(@Param("ids")Stringids);}// UserService.javaimportorg.springframework.stereotype.Service;importjavax.annotation.Resource;importjava.util.List;importcom.example.entity.User;importcom.example.mapper.UserMapper;@ServicepublicclassUserService{@ResourceprivateUserMapperuserMapper;publicList<User>getUserListByIds(){// 传入逗号分隔的 ID 字符串Stringids="1,3,5";// 调用 Mapper 方法returnuserMapper.selectUserByIds(ids);}}#{ids}接收的必须是逗号分隔的字符串(如"1,3,5"),不能是 List 集合直接传入(如果是 List,需要先转成字符串)。List<Integer>idList=Arrays.asList(1,3,5);Stringids=String.join(",",idList.stream().map(String::valueOf).toArray(String[]::new));FIND_IN_SET()无法使用索引,数据量大时性能较差,建议优先用IN (1,3,5)(MyBatis 中可通过<foreach>实现)。FIND_IN_SET(3, '1,3,5')→ 返回 2(第2个位置)FIND_IN_SET(6, '1,3,5')→ 返回 0(未找到)如果你的参数是 List 集合,更推荐用<foreach>拼接IN,性能更好:
<selectid="selectUserByIds"resultType="com.example.entity.User">SELECT * FROM user WHERE id IN<foreachcollection="ids"item="id"open="("separator=","close=")">#{id}</foreach></select>对应的接口:
List<User>selectUserByIds(@Param("ids")List<Integer>ids);FIND_IN_SET(id, #{ids})中,#{ids}必须传入逗号分隔的字符串,函数返回匹配的位置(非0则命中);<foreach>拼接IN;IN写法)。