MySQL 使用 order by field 自定义排序
2021-12-23 本文已影响0人
思念_似水流年
- MySQL 查询时,如果不带
order by
,会根据主键来排序,从小到大返回查询结果; - 带
order by
时,可指定按字段升序 ASC 或降序 DESC:
SELECT * FROM project_case where
case_id in (119, 113, 117)
order by case_id asc;
SELECT * FROM luckyframe.project_case where
case_id in (119, 113, 117)
order by case_id desc;
- 若想结果按照指定的字段和指定的顺序进行排序时,需要用到
order by field
关键字:
SELECT * FROM project_case where
case_id in (119, 113, 117)
order by field(case_id, 119, 113, 117);
返回结果按照指定的字段和指定的顺序进行排序:
指定顺序排序
MyBatis 使用 order by field 语法
<select id="selectSortedProjectCaseByIds" parameterType="String" resultMap="ProjectCaseResult">
SELECT * FROM project_case where
case_id in
<foreach collection="caseIdList" item="caseId" open="(" close=")" separator=",">
#{caseId}
</foreach>
order by field
<foreach collection="caseIdList" item="caseId" open="(case_id," close=")" separator=",">
#{caseId}
</foreach>
</select>
Mapper.java 中调用的代码如下:
List<ProjectCase> selectSortedProjectCaseByIds(@Param("caseIdList") List<Integer> caseIdList);
传递的 caseIdList 是已经排好序的列表。