【问题标题】:How to find the last 7 days Records in sqlite?如何在sqlite中找到最近7天的记录?
【发布时间】:2010-04-30 10:38:53
【问题描述】:

我想知道过去 7 天的记录。我想在 where 条件下写一个查询。我对sqlite有非常基本的了解。请帮我解决这个问题。

【问题讨论】:

    标签: java android sqlite


    【解决方案1】:

    您需要将日期存储在数据库的某一列中。在我的应用程序中,我使用 timeIntervalSinceReferenceDate 将 NSDate(显然是 iPhone)转换为双精度以存储在数据库中。鉴于我可以查询日期范围。

    我编写了计算过去/未来 X 天午夜的 NSDate 的函数,我用它来确定查询的 startDate 和 endDate。以下是代码的摘录,可以为您提供一些想法:

    char selectQuery[MAX_STR];
    sprintf(selectQuery, "SELECT DateTime FROM Journal WHERE DateTime >= %f AND DateTime < %f;", 
                         [startDate timeIntervalSinceReferenceDate],
                         [endDate   timeIntervalSinceReferenceDate]);
    

    我不想将 NSDate 转换为日期时间字符串,因为我不相信所有不同时区和不同区域设置日期格式的来回转换。

    【讨论】:

    • 这是对 java 的实际查询: select * from table_name where strftime('%Y-%m-%d',field_name)>=date('now','-6 days')和 strftime('%Y-%m-%d',field_name)
    【解决方案2】:

    sqlite 不会跟踪您的表格行是何时添加的。如果您需要这种行为,您应该添加一个时间戳列,并在插入新行时在其中设置当前时间。

    【讨论】:

    • 我可以使用 between 子句吗?我的意思是 select * from tablename order by columnname between currentdate and currentdate-7;
    • 在sqlite中不存在Between。您可以执行 SELECT * FROM tablename WHERE columnname > currentdate - 60*60*24*7 ORDER BY columnname。您应该查看 sqlite 语法:sqlite.org/lang.html。我假设您将日期存储为 UNIX 时间戳
    • BETWEEN 确实存在于 SQLite 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 2011-07-24
    • 2021-06-01
    相关资源
    最近更新 更多