1. 问题说明
SELECT * FROM tableName WHERE tableField IN ('','')
姑且不说这种 SQL 的效率和可优化和替代性,就当前问题在 MySQL、Greenplum 数据库没有 1000 的限制。
2. 解决方法
解决的方法较多,这里使用的是 JDK8 的 stream 方法,代码如下:
private String getInStrByList(List<Map<String, Object>> list) {
int listSize = list.size();
List<Map<String, Object>> tempRecordList;
int lengthControl = 1000;
List<String> inStrSegmentList = new ArrayList<>();
if (listSize <= lengthControl) {
return list.stream().map(oneMap-> MapUtils.getString(oneMap, "fieldName")).collect(Collectors.joining("','", " table_field in ( '", "' ) "));
} else {
double number = listSize * 1.0 / lengthControl;
int n = ((Double) Math.ceil(number)).intValue();
for (int i = 0; i < n; i++) {
int iLength = i * lengthControl;
int end = lengthControl * (i + 1);
if (end > listSize) {
end = listSize;
}
tempRecordList = list.subList(iLength, end);
String inStrSegment = tempRecordList.stream().map(oneMap -> MapUtils.getString(oneMap, "fieldName")).collect(Collectors.joining("','", "'", "'"));
inStrSegmentList.add(inStrSegment);
}
}
return inStrSegmentList.stream().collect(Collectors.joining(" ) or table_field in ( "," ( table_field in ( "," ) )"));
}
字符串的使用举例:
<select id="geDataList" parameterType="java.util.Map" resultType="java.util.Map">
SELECT * FROM table_name
<where>
<if test="inStr != null and inStr != ''">
AND ${inStr}
</if>
</where>
</select>
|