我的活动时间以YYYY-MM-DD HH:MM:SS的形式存储。
我要做的是找到事件的所有实例,它发生在前一个Trigger之后7个多小时。在阅读SQLite Date文档后,我不确定最简单的方法。我想我不得不以某种方式使用strftime,但我真的不确定如何处理它。
这是我必须建立的基本查询:
SELECT * FROM Event WHERE Event.DateTime (is more than 7 hours after) (SELECT Trigger.DateTime FROM Trigger WHERE Event.DateTime > Trigger.DateTime)
我目前设置的测试数据如下:
DROP TABLE IF EXISTS "Event";
CREATE TABLE "Event" ("DateTime" TEXT, "ID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE );
INSERT INTO "Event" VALUES('2000-01-01 08:00:00',1);
INSERT INTO "Event" VALUES('2000-01-01 09:00:00',2);
INSERT INTO "Event" VALUES('2000-01-01 14:00:00',3);
INSERT INTO "Event" VALUES('2000-01-01 15:00:00',4);
INSERT INTO "Event" VALUES('2000-01-01 20:00:00',5);
DROP TABLE IF EXISTS "Trigger";
CREATE TABLE "Trigger" ("DateTime" TEXT, "ID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE );
INSERT INTO "Trigger" VALUES('2000-01-01 00:00:01',1);
INSERT INTO "Trigger" VALUES('2000-01-01 10:00:01',2);
所以它应该从事件中返回1,2和5,因为那些是触发后超过7小时的事件。
答案 0 :(得分:1)
是否有理由要针对Trigger.DateTime测试Event.DateTime两次?我认为这也应该有效:
SELECT * FROM Event
WHERE EXISTS(SELECT 1 FROM Trigger
WHERE datetime(Event.DateTime,'+7 hours') > Trigger.DateTime)
<强>更新强>
由于您只想与最新的触发器进行比较,因此更像是这样:
SELECT * FROM Event
WHERE EXISTS(SELECT MAX(Trigger.DateTime) newest FROM Trigger
HAVING datetime(Event.DateTime,'-7 hours') > newest)
修改强>
SELECT * FROM Event
WHERE NOT EXISTS(SELECT 1 FROM Trigger
WHERE datetime(Event.DateTime,'-7 hours') <= Trigger.DateTime)
SELECT * FROM Event
WHERE datetime(Event.DateTime,'-7 hours') >
(SELECT MAX(Trigger.DateTime) newest FROM Trigger)
<强> EDIT2 强>
SELECT * FROM Event
WHERE NOT EXISTS(SELECT 1 FROM Trigger
WHERE Trigger.DateTime BETWEEN datetime(Event.DateTime,'-7 hours') AND Event.DateTime)
SELECT * FROM Event
WHERE datetime(Event.DateTime,'-7 hours') >
(SELECT MAX(Trigger.DateTime) newest FROM Trigger
WHERE Trigger.DateTime < Event.DateTime)
答案 1 :(得分:0)
怎么样
SELECT * FROM Event
WHERE datetime(Event.DateTime,'+7 hours') > (SELECT Trigger.DateTime FROM Trigger
WHERE Event.DateTime > Trigger.DateTime)