問題:for循環執行sql查詢,想優化一下,想著把for循環組合成一條sql語句執行代碼:
List<DataInfo> dataPotints = (ArrayList<DataInfo>) request.getAttribute("dataPotints");
ArrayList<IotDataHistory> iotDataHistories = new ArrayList<IotDataHistory>();
for (int i = 0; i < dataPotints.size(); i++) {
//這里執行for循環,通過mybatis查詢,并將查詢的數據放到list里面
iotDataHistories.add(**dataService.getLastData(dataPotints.get(i))**);
}
String responsebody = handlerJson(iotDataHistories);
log.info("獲取最后一條數據返回的json數據" + responsebody);
return responsebody;
具體應該如何優化,如何合并成一條sql,改怎么合并?用union、or 還是 其它的 ?
6 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
select * from table where xx in ('a','b','c');
表示查詢table表里面xx等于a,b,c的記錄(mysql數據庫)

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
把循環移動到mapper,用動態生成sql
比如 你要執行10個 insert into table_name (列1, 列2,...) VALUES (值1, 值2,....)
在mapper里可以拼成 insert into table_name (列1, 列2,...) VALUES (值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....),(值1, 值2,....)
添加回答
舉報
0/150
提交
取消