SQL lite组合Query

时间:2016-08-15 09:43:34

标签: android android-sqlite

我编写了以下3个查询。但是需要将所有3个查询组合起来才能获得最终查询。

查询1:获取2个日期之间的所有记录。

  String selectQuery = "SELECT  * FROM " + TABLE_ALL_RECORD_MAIN + " WHERE " + KEY_DATE + ">=" + fro + " AND " + KEY_DATE + "<=" + to + " OR " + OUTDATE + ">=" + fro + " AND " + KEY_OUTDATE + "<=" + to;
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(selectQuery, null);

查询2:获取大于“from_amount”且小于“to_amount”的所有记录。

  String selectQuery_amount = "SELECT  * FROM " + TABLE_ALL_RECORD_MAIN + " WHERE " + KEY_AMOUNT + ">=" + from_amount + " AND " + KEY_AMOUNT + "<=" + to_amount;
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(selectQuery_amount, null);

查询3:获取与search_name匹配的所有记录。

  String selectQuery_amount = "SELECT  * FROM " + TABLE_ALL_RECORD_MAIN + " WHERE " KEY_NAME + " like '" + search_name + "'";
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(selectQuery_amount, null);

Reqiured Query:

1-编写包含所有上述查询的查询。

例如:从2014年4月5日到2015年9月8日获取用户“杰克”的金额为50000到60000的所有记录。

2 个答案:

答案 0 :(得分:1)

  String selectQuery_amount = "SELECT  * FROM " + TABLE_ALL_RECORD_MAIN +
  " WHERE " KEY_NAME + " ='" + search_name + "' AND "KEY_DATE 
  +" BETWEEN "+fro +" AND "+ to +" AND "+ KEY_AMOUNT +"BETWEEN "
  +from_amount +" AND "+to_amount;

  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(selectQuery_amount, null);

  //Date format would be like this  
  SELECT * FROM test WHERE date BETWEEN "2011-01-11" AND "2011-8-11"

答案 1 :(得分:0)

String selectQuery = "SELECT  * FROM " + TABLE_ALL_RECORD_MAIN + " WHERE "+
KEY_DATE + ">=" + fro + " AND " + KEY_DATE + "<=" + to + " OR " + OUTDATE + ">=" + fro + " AND " + KEY_OUTDATE + "<=" + to+"AND "+
KEY_AMOUNT + ">=" + from_amount + " AND " + KEY_AMOUNT + "<=" + to_amount+"AND "+
KEY_NAME + " like '" + search_name + "'";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

请注意查询中每行末尾的"AND "关键字,用于连接查询。作为旁注,考虑使用getReadableDatabase()而不是getWritableDatabase()这只是一个查询,在这种情况下没有理由获取可写实例。