SQLite的时间差判断--删除N天前的数据的两种写法

时间:2024-04-23 08:36:54

比如我有个用SQLite Studio创建的Sqlite3类型数据库,里面有个表名为StatisticsData的表结构是 :

-- 表:StatisticsData
CREATE TABLE "StatisticsData" ( "Id" TEXT NOT NULL, "MachineName" NVARCHAR, "SessionId" INTEGER, "ProcessId" INTEGER, "ProcessName" NVARCHAR, "ProcessRunningStatus" NVARCHAR, "WorkingSetMemory" NVARCHAR, "WorkingSetPrivateMemory" NVARCHAR, "WorkingSetPeak" NVARCHAR, "ThreadCount" NVARCHAR, "HandleCount" NVARCHAR, "TotalProcessorTime" NVARCHAR, "UserProcessorTime" NVARCHAR, "PrivilegedProcessorTime" NVARCHAR, "StartTime" DATETIME, "ExitTime" DATETIME, "Domain" NVARCHAR, "UserName" NVARCHAR, "FileName" NVARCHAR, "Arguments" NVARCHAR, "WorkingDirectory" NVARCHAR, "CreatedTime" DATETIME, PRIMARY KEY ("Id" ASC), CONSTRAINT "PK_Id" UNIQUE ("Id" ASC) )

举例:

今天是2017-08-10,要删除7天前的数据,也就是说,所有小于等于2017-08-03都要被删掉。

写法1:忽略时间精度,直接比较日期,删除N天前的数据。

DELETE FROM StatisticsData WHERE date('now', '-7 day') >= date(CreatedTime);

 写法2:计算时间精度,比较日期和时间,删除N天前的数据。

DELETE FROM StatisticsData WHERE julianday('now') - julianday(CreatedTime) >= 7;

有关时间运算和比较函数的官方教程:http://www.sqlite.org/lang_datefunc.html

翻译自官网的中文参考:http://www.cnblogs.com/ygm900/p/4460644.html