如何在 sqlite 中使用 UPSERT 以保留 created_at 时间?

How do I use UPSERT in sqlite such that created_at time is preserved?

我正在尝试将此 INSERT 语句替换为 UPSERT(现在在 sqlite 中受支持)

 55     await db.query(
 56       "INSERT OR REPLACE INTO urls(url, title, excerpt, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",
 57       [url, article.title, article.excerpt, new Date().toISOString(), new Date().toISOString()],
 58     );

我想保留原始的 created_at 时间戳和其他属性(除了 url 这是关键),如果该行已经存在,则可以更新。

如果您还可以将 count = count + 1 列添加到 table 以跟踪观看次数,则可加分。

如果列 url 有唯一约束,则 UPSERT 的语法为:

INSERT INTO urls(url, title, excerpt, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(url) DO UPDATE 
SET title = EXCLUDED.title, 
    excerpt = EXCLUDED.excerpt, 
    updated_at = EXCLUDED.updated_at;

如果还有一列count:

INSERT INTO urls(url, title, excerpt, created_at, updated_at, count) VALUES (?, ?, ?, ?, ?, 1) 
ON CONFLICT(url) DO UPDATE 
SET title = EXCLUDED.title, 
    excerpt = EXCLUDED.excerpt, 
    updated_at = EXCLUDED.updated_at,
    count = count + 1;

或者,如果您定义了 count,默认值为 1,则可以从 INSERT 列表中省略它:

INSERT INTO urls(url, title, excerpt, created_at, updated_at) VALUES (?, ?, ?, ?, ?) 
ON CONFLICT(url) DO UPDATE 
SET title = EXCLUDED.title, 
    excerpt = EXCLUDED.excerpt, 
    updated_at = EXCLUDED.updated_at,
    count = count + 1;