我对此代码有疑问:
im = stat.executeQuery("SELECT * FROM imones");
while (im.next()) {
sask = stat2.executeQuery("SELECT * FROM saskaitos WHERE imone='" + im.getInt("id") + "'");
while (sask.next()) {
suma = suma + Integer.parseInt(sask.getString("suma"));
kvit = stat3.executeQuery("SELECT * FROM kvitai WHERE sask_nr='" + sask.getInt("sask_nr") + "'");
while (kvit.next()) {
suma = suma - Integer.parseInt(kvit.getString("suma"));
}
kvit.close();
}
sask.close();
//if (suma > 0) {
imone = im.getString("pav");
skola = suma;
DefaultTableModel y = (DefaultTableModel) pagrindinis.visos_skolos_table.getModel();
Vector rowData = new Vector();
rowData.add(imone);
rowData.add(skola);
y.addRow(rowData);
//}
}
im.close();
我只得到一个循环(而(im.next()))因为' sask'查询没有结果,它关闭' im'结果集和多语句没有帮助。我怎样才能使这段代码有效?谢谢!
答案 0 :(得分:1)
不需要嵌套循环,可以使用一个连接表并汇总金额的SQL语句来完成。我显然没有所有的列名,但您应该能够替换我自己使用的名称:
SELECT company.name,
SUM(bill.amount) - SUM(cheque.amount) AS amount
FROM imone AS company
INNER JOIN saskaitos AS bill ON company.id = bill.imone
LEFT JOIN kvitai AS cheque ON bill.sask_nr = cheque.sask_nr
GROUP BY company.name;