MyBatis 多参数,in顺序查询

本文介绍了一种使用Redis存储推荐群组ID的方法,并通过数据库查询这些群组的详细信息,确保了查询结果按照Redis中存储的顺序返回。此外,还讨论了SQL查询中保持特定顺序的几种方法及其实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、从redis按照顺序查询出推荐群组(id),然后通过in查询数据库得到群组的详细信息,并按照in的顺序返回

/**
 * 获取推荐群列表
 * @return
 */
public List<Groups> selectTopGroups() {
	CacheManager cm=CacheManager.getInstance();
	Set<String> s=cm.getZSetMembers(KeyParam.RECOMMEND_GROUP);
	
	logger.debug("推荐列表" + s);
	
	List<Integer> groupIds = null; 
	if(s!=null && s.size() > 0){
		groupIds = new ArrayList<Integer>();
		for(String g : s){
			try {
				Integer gId = Integer.parseInt(g);
				groupIds.add(gId);
			} catch (Exception e) {
			}
		}
	}
	if(groupIds != null && groupIds.size() > 0){
    	Map<String, Object> paramMap = new HashMap<String, Object>();
    	StringBuilder sortStr = new StringBuilder();
    	for(Integer id : groupIds){
    		sortStr.append(id).append(",");
    	}
    	sortStr.delete(sortStr.lastIndexOf(","), sortStr.length());
    	
    	paramMap.put("groupIdList", groupIds);
    	paramMap.put("sortStr", sortStr.toString());
    	
		return this.mapperFactory.groupsMapper.selectGroupListBySort(paramMap);
	}
	return null;
}
mapper.java
/**
 * 根据群id获取群的全部信息,按照list里面的序号排序
 * @param paramMap 参数map <br/>
 *  groupIdList  --- List<Integer>   <br/>
 *  sortStr ---- String   排序字符串,格式:'1932,2342,3242' 也就是集合中的id,已逗号隔开
 */
List<Groups> selectGroupListBySort(Map<String, Object> paramMap);
mapper.xml
<!-- 根据群id获取群的全部信息,按照list里面的序号排序 -->
  <select id="selectGroupListBySort" resultMap="BaseResultMap" parameterType="java.util.Map" >
   select
   <include refid="Base_Column_List" />
   from groups
   where id in
    <foreach collection="groupIdList" item="item" index="index" open="(" close=")" separator=",">
     #{item}
  </foreach>
  order by find_in_set(id, #{sortStr,jdbcType=VARCHAR}) asc;
 </select>

SQL基础:
--按照in的顺序查询

--这种有bug
select u.id,u.name,u.sex,u.photo,instr('4,7,17,20,5,6',u.id) as i from user u where u.id in (4,7,17,20,5,6) order by i asc;

--bug案例
select u.id,u.name,u.sex,u.photo,instr('11,1,111',u.id) as i from user u where u.id in (11,1,111) order by i asc;    --instr函数的含义就是找u.id在前面'11,1,111'的索引,于是这种就会有bug

--bug改进方案(然并卵)
select u.id,u.name,u.sex,u.photo from user u where u.id in (11,1,111) order by instr(',11,1,111,' , ','+u.id+',') asc;

--最好的方案
select u.id,u.name,u.sex,u.photo from user u where u.id in (11,1,111) order by find_in_set(u.id,'11,1,111') asc;


--普通查询(会默认按照id排序)
select u.id,u.name,u.sex,u.photo from user u where u.id in (4,7,17,20,5,6);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值