解决SQL语句 in 集合过长的问题
问题:在公司写查询时候,在写人员权限查询时候,部门性质表是一张层层嵌套迭代的表(部门id,父部门id,部门级别),需求场景需要找到部门所有下级部门,按权限查询数据。
正常思路:
查询当前所在部门 编码 级别 循环迭代下级部门 拿下级部门编码 父编码 级别 继续循环
mapper层入参:
List<Po> queryUser(@Param("deptCode") List<List<String>> deptCode);
<if test="deptCode != null and >0">
and
<foreach collection="deptCode" index="index" item="idsItem" open="(" separator="or" close=")" >
b.OBJ_MRC in
<foreach collection="idsItem" index="index" item="item" open="(" separator="," close=")" >
#{item}
</foreach>
</foreach>
</if>
SQL in集合长度大于1000会报错(解决方法把一个集合拆分为多个小于集合)
切分in集合两种方法
public static List<List<String>> splitList(List<String> list, int len) {
//list为需要拆分的集合 len 拆分的长度
if (list == null || list.size() == 0 || len < 1) {
return null;
}
List<List<String>> result = new ArrayList<List<String>>();
int size = list.size();
int count = (size + len - 1) / len;
for (int i = 0; i < count; i++) {
List<String> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
result.add(subList);
}
return result;
}
public Map groupList(List list) {
int listSize = list.size();
int toIndex = 1000;
Map map = new HashMap(); //用map存起来新的分组后数据
int keyToken = 0;
for (int i = 0; i < list.size(); i += 1000) {
if (i + 1000 > listSize) { //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
toIndex = listSize - i;
}
List newList = list.subList(i, i + toIndex);
map.put("keyName" + keyToken, newList);
keyToken++;
}
return map;
}
改进
当in集合 集合长度特别长的时候 sql查询效率会非常低下,数据量特别大的时候不建议使用这种方式。
改进方式
新增部门横向拉伸表 把纵向循环迭代的部门表 水平横向拉伸 权限查询时使用连表查询的方式提高SQL查询效率
1.定时任务,从原表拉数据定时更新部门横向拉伸表
2.从BI大数据部门数据平台导数