我有这个数据库
Table [Ticks]
Fields: 2
[Value]: INT
[Time]: DATETIME
Indexes: 1
[TicksIdx]
[Time]
[Value]
Triggers: 0
Table constraints:
Primary Key:
Fields:
On Conflict:
Foreign Keys: 0
Unique constraints: 0
Check constraints: 0
Table [Ticks] end
我想计算从 10 小时前到现在的 value=-1 和 Time < (Now-10 hours) 的所有记录
我有这个查询,总是返回 0
select count(*) from Ticks where Value=-1 and
time>=datetime('now', '-10 hours')
如果我将查询更改为此,它将返回所有记录
select count(*) from Ticks where Value=-1 and
time<datetime('now', '-10 hours')
我有时间值最近超过 10 小时的记录
最佳答案
解释
您的问题将是由于存储在时间列中的值不是可识别的格式,也很复杂,因为没有比较喜欢。
SQLite 识别的格式可以在这里找到 SQL As Understood By SQLite - Date And Time Functions - Time Strings .
例如 YYYY-MM-DD HH:MM:SS (例如 2018-12-09 12:40:01)就是这样一种公认的格式。
您查询的是(假设来自 c# 的 9/12/2018 12:40:01 AM 并且运行时相同)说:-
由于这些值是非数字的,因此会进行逐个字符的比较,因此使用这些时间 9 大于 2(当然,如果它是 09/12 ......那么就不是)。
如果基础数据采用可识别的格式,则确保类似比较的正确方法是确保双方比较 dimetime 的实际情况,因此 SQL 应该是:-
SELECT count(*) FROM Ticks WHERE Value=-1 AND datetime(time) >= datetime('now', '-10 hours')
-注意您可能需要合并本地时间来调整时间,例如
datetime(time) >= datetime('now','localtime', '-10 hours')
The "localtime" modifier (12) assumes the time string to its left is in Universal Coordinated Time (UTC) and adjusts the time string so that it displays localtime. If "localtime" follows a time that is not UTC, then the behavior is undefined. The "utc" modifier is the opposite of "localtime". "utc" assumes that the string to its left is in the local timezone and adjusts that string to be in UTC. If the prior string is not in localtime, then the result of "utc" is undefined.
修复
要解决此问题,您需要
如果时间是插入刻度行的当前时间,那么您可以使用
time DATETIME DEFAULT CURRENT_TIMESTAMP
作为 的定义时间列而不提供 的值时间插入行时的列。否则,您应该在存储值之前将值的格式更改为可识别的格式。
关于SQLite 选择计数 10 小时前的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686708/