我有一个BIG交易表。我想在最后一分钟插入的事务中找到一个特定字段(卡号),因此搜索整个表是不合理的。所以我想搜索前20行。
这是我的代码:
public boolean isCardTapedInLastMinute(String date, String time,String UID) {
String oneMinuteBefore = getOneMinuteBefore(time);
String tables = TRX.TABLE_NAME;
String[] columns = {TRX._ID};
String selection = TRX.COLUMN_NAME_TRX_DATE + " = ? AND " +
TRX.COLUMN_NAME_TRX_TIME + " >= ? AND " +
TRX.COLUMN_NAME_CARD_ID + " = ?";
String[] selectionArgs = {date, oneMinuteBefore, UID};
String sortOrder = TRX.COLUMN_NAME_TRX_DATE
+ BusDBContract.SORT_ORDER_DESC
+ ", "
+ TRX.COLUMN_NAME_TRX_TIME
+ BusDBContract.SORT_ORDER_DESC;
String limit = "1";
Cursor cursor = query(selection, selectionArgs, columns, tables, sortOrder, limit);
if (null == cursor) {
return false;
}
if (!cursor.moveToFirst()) {
cursor.close();
return false;
}
return true;
}
和查询方法:
private Cursor queryWith(String selection, String[] selectionArgs, String[] columns, String tables, String sortOrder, String limit) {
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(tables);
Cursor cursor;
try {
cursor = builder
.query(
mBusOH.getReadableDatabase(),
columns,
selection,
selectionArgs,
null,
null,
sortOrder,
limit);
} catch (SQLException e) {
Log.e(TAG, "[query]sql_exception: " + e.getMessage());
return null;
}
return cursor;
}
它正常工作,它会搜索整个表格。 15000行需要大约50-100毫秒,但它可能更大,我想通过搜索前20行来优化它。
最好的方法是什么?
编辑: db scheme: