计算联接查询行的最快方法

时间:2019-04-24 12:10:54

标签: java mysql jdbc

我想通过mysql jdbc在Java中执行以下查询:SELECT COUNT (*) FROM ORDERS, CUSTOMER WHERE O_ORDEYKEY = O_CUSTKEY

我有此代码:

Connection conn = new DatabaseConnection().createMySQLConnection();
int totalRows=0;
  for(int j=0;j<tables.size();j++)
        {
            Statement stmt = null;
            ResultSet rs = null;
            int rowCount = -1;
            try {
                conn.setAutoCommit(false);
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tables.get(j) 
 + " WHERE O_ORDERKEY = O_CUSTKEY;");
                rs.next();
                rowCount = rs.getInt(1);
                totalRows= totalRows+rowCount;
            } finally {
                rs.close();
                stmt.close();
            }

        }

但是我想更快地运行它。我该怎么办?

1 个答案:

答案 0 :(得分:1)

为了便于阅读,您应该避免基于位置使用旧的隐式联接sintax并使用SQL标准(自1992年起)显式联接sintax

SELECT COUNT (*) 
FROM ORDERS
INNER JOIN CUSTOMER  ON  ORDERS.O_ORDEYKEY = CUSTOMER.O_CUSTKEY

为了获得更好的性能,请确保您在

上有一个索引

表ORDERS列O_ORDEYKEY

表CUSTOMER列O_CUSTKEY