如何用条件替换冲突(对于SQLite)?

时间:2016-10-25 07:04:38

标签: sql sqlite

我在下面有一个SQL来创建一个表。它将取代名称冲突的地方。

CREATE TABLE IF NOT EXISTS MYTABLE (
    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    NAME TEXT NOT NULL,
    DATE INTEGER NOT NULL,
    CONSTRAINT UNIQUE_NAME UNIQUE (NAME) ON CONFLICT REPLACE
)

但是,我想仅在日期较新(数量较大)时更换,或者如果日期较旧则忽略新行。我怎么能改变上面的SQL(for SQLite)语句才能实现呢?

1 个答案:

答案 0 :(得分:1)

使用表格约束无法执行此操作,您必须改为使用triggers

CREATE INDEX just_some_index ON MyTable(Name);

CREATE TRIGGER MyTable_Name_insert_newer
BEFORE INSERT ON MyTable
FOR EACH ROW
WHEN (SELECT Date FROM MyTable WHERE Name = NEW.Name) <= NEW.Date
BEGIN
    DELETE FROM MyTable
    WHERE Name = NEW.Name;
END;

CREATE TRIGGER MyTable_Name_insert_older
BEFORE INSERT ON MyTable
FOR EACH ROW
WHEN (SELECT Date FROM MyTable WHERE Name = NEW.Name) > NEW.Date
BEGIN
    SELECT RAISE(IGNORE);
END;

(在SQLite中,没有结果的标量子查询只返回NULL,因此插入新行会使两个WHEN子句都失败。)