SQLite选择今天和前一天的所有记录

时间:2013-02-07 13:38:45

标签: android sqlite date select

我的数据库中有以下表格:

    database.execSQL("create table " + TABLE_LOGS + " (" 
            + COLUMN_ID + " integer primary key autoincrement," 
            + COLUMN_ID_DAY_EXERCISE + " integer not null,"
            + COLUMN_REPS + " integer not null,"
            + COLUMN_WEIGHT + " real not null,"
            + COLUMN_1RM + " real not null,"
            + COLUMN_DATE + " integer not null"
            + ")");

我将一个unix时间戳存储在COLUMN_DATE字段中(整数)。

现在我有以下功能可以抓取所有记录:

public Cursor fetchCurrentLogs(long dayExerciseDataID) {
    // where day = today
    Cursor cursor = database.rawQuery("select " + MySQLiteHelper.COLUMN_ID + "," + MySQLiteHelper.COLUMN_REPS + ", " + MySQLiteHelper.COLUMN_WEIGHT + " " +
            "from " + MySQLiteHelper.TABLE_LOGS + " " +
            "where " + MySQLiteHelper.COLUMN_ID_DAY_EXERCISE + " = '" + dayExerciseDataID + "'", null);
    if (cursor != null) { cursor.moveToFirst(); }
    return cursor;
}

现在我想做的是,我想让这个功能只抓住今天的记录。

然后我想要使另一个函数完全相同,但是我没有获取今天的记录,而是希望它获取前一天的记录。以前,我的意思是最近一天有记录,而不是今天。所以它可能是昨天,或3天前,或一个月前。

我知道在MySQL中你可以做这样的事情当天:

where date_format(from_unixtime(COLUMN_DATE), '%Y-%m-%d')= date_format(now(), '%Y-%m-%d')

SQLite的等效内容是什么?

另外,如上所述,任何人都可以帮我解决前一天的where子句吗?

非常感谢。

4 个答案:

答案 0 :(得分:16)

String sql = "SELECT * FROM myTable WHERE myDate >= date('now','-1 day')"; 
Cursor mycursor = db.rawQuery(sql);

修改

SELECT * from Table1 where myDate = (select max(myDate) from Table1 WHERE myDate < DATE('now') )

答案 1 :(得分:4)

请参阅date/time functions documentation

SELECT *
FROM MyTable
WHERE myDate >= date('now', '-1 days')
  AND myDate <  date('now')

答案 2 :(得分:0)

可能是为时已晚,但它可以帮助某人。我和以前的开发人员没有什么不同,我只是想把我的版本,可能它甚至不是最好的......

    String selectQuery = "SELECT * FROM "+Your_table+" 
WHERE ("+Column_1+" = "+Value_For_Column1+" AND date("+Your_Column_With_Time_Values+") == date('now')) AND 

"+Some_Other_Column+" = "+Some_Other_Value+" OR "+Some_Other_Column+" = "+Some_Other_Value+" ORDER BY "+Your_Column+" DESC";

如果可能存在某些错误,可能很容易因字符串连接而导致错误。 谢谢!!

答案 3 :(得分:-2)

不要在SQL语句中进行转换。在Java方法中进行转换。让您的Java方法创建完整的SQL语句。您只需要一个将Java DateTime转换为unix格式的函数。

Cursor cursor = database.rawQuery("select " + MySQLiteHelper.COLUMN_ID + "," + MySQLiteHelper.COLUMN_REPS + ", " + MySQLiteHelper.COLUMN_WEIGHT + " " +
            "from " + MySQLiteHelper.TABLE_LOGS + " " +
            "where " + MySQLiteHelper.COLUMN_ID_DAY_EXERCISE + " = '" + dayExerciseDataID + 
            " OR " + MySQLiteHelper.COLUMN_ID_DAY_EXERCISE + " = '" + previousDay(dayExerciseDataID) +
"'", null);

您只需要创建previousDay方法。