两个表之间循环查询引发的血案~~~~~~~~~~~~~~
有两个表ta、tb
ta{
idx;
type
}
tb{
idx;
price
}
逻辑是这样的:
先查询出ta.type=某个值的ta.idx,返回的ta.idx可能有数万条记录;
然后针对上面查询出的数万条记录,逐一在tb中查询tb.idx=ta.idx的price,每条ta.idx可能对应tb中的上万条tb.idx
即:
- Java code
strSQL = "select idx from ta where type = 'xxx'";rsA = stmtA.executeQuery(strSQL);//这里的rsA包含数万条记录while(rsA.next()){ //这里将会是数万次循环 strSQL = "select price from tb where idx = " + rsA.getInt("idx"); rsB = stmtB.executeQuery(strSQL); while(rsB.next()){ 这里又是数万次循环 price += rsB.getInt("price"); }}速度奇慢无比啊!!
我知道这种循环的方式是最笨的了,求好办法!
[解决办法]
select TA.idx,SUM(TB.PRICE) AS AMOUNT from ta JOIN TB ON TA.IDX = TB.IDX where TA.type = 'xxx'
GROUP BY TA.IDX
[解决办法]
- SQL code
select idx,price from tb where idx in ( select idx from ta where type = XXX )