当我在MySQL中使用IN语句进行查询时
例如SELECT * FROM Course WHERE teacher_id in ("6553","2145","3162"),从课程表里使用教师id查询记录,这时我希望返回的记录是按("6553","2145","3162")的顺序,但是发现并不是,而是("2145","3162","6553")的顺序,进行了排序。
可以使用ORDER BY FIELD语句。
SELECT * FROM Course WHERE teacher_id in ("6553","2145","3162") ORDER BY FIELD(tracher_id,"6553","2145","3162"),其中tracher_id指定排序的字段,之后给出顺序,返回的结果即可满足按IN中指定的顺序排序。
在MyBatis或MyBatisPlus中,可以手动拼接sql语句达到同样的效果。
private String makeOrderByFieldSql(String fieldName, Listfields) { StringBuilder orderSql = new StringBuilder(); orderSql.append("ORDER BY FIELD(").append(fieldName).append(","); for (String field : fields) { orderSql.append("\"").append(field).append("\"").append(","); } //去除最后一个 ",",加上括号 orderSql.deleteCharAt(orderSql.length() - 1).append(")"); return orderSql.toString(); }
//构建LambdaQueryWrapper LambdaQueryWrappercourseLambdaQueryWrapper = new LambdaQueryWrapper<>(); //调用方法生成sql语句 String orderSql = this.makeOrderByFieldSql("teacher_ids", teacherIds); //使用last函数在查询的最后拼接sql语句 courseLambdaQueryWrapper.in(CourseResource::getTeacherId, resourceIds).last(orderSql); //查询得到结果 courses = courseService.list(courseLambdaQueryWrapper);
上一篇:Java集合转int数组