目标效果:根据in中元素的顺序返回结果
查询id为(2,4,1,3)的数据,并按此顺序返回
第一次尝试
select id, name from tb_shop where id in (2, 4, 1, 3);
期待效果
实际效果
正确的语句
select id, name from tb_shop where id in (2, 4, 1, 3) order by field(id, 2, 4, 1, 3);
项目中实现
方法一:自定义mapper.xml
mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hmdp.mapper.ShopMapper">
<select id="queryShopAndSortByIds" resultType="com.hmdp.entity.Shop" parameterType="java.util.List">
SELECT *
FROM tb_shop
WHERE id IN <foreach collection="shopIds" item="shopId" open="(" separator="," close=")"> #{shopId} </foreach>
ORDER BY field(id, <foreach collection="shopIds" item="shopId" separator=","> #{shopId} </foreach>)
</select>
</mapper>
mapper
package com.hmdp.mapper;
import com.hmdp.entity.Shop;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ShopMapper extends BaseMapper<Shop> {
List<Shop> queryShopAndSortByIds(@Param("shopIds") List<Long> shopIds);
}
impl
List<Long> ids = new ArrayList<>(list.size());
List<Shop> shops = getBaseMapper().queryShopAndSortByIds(ids);
方法二:利用last()拼接order by field(id, id1, id2, id3…)的sql语句
List<Long> ids = new ArrayList<>(list.size());
String idStr = StrUtil.join(",", ids);
List<Shop> shops = lambdaQuery().in(Shop::getId, ids).last("ORDER BY FIELD(id," + idStr + ")").list();