当我尝试实现的是一个触发器,它将在进行插入时更新表,如果表已经有了articleId,那么articleIsLiked应该更改为0,否则它应该插入articleId和articleIsLiked to 1.当我进行插入操作时,每次尝试运行插入查询而不是更新记录时都会生成一条新记录。
CREATE TRIGGER test_update
AFTER INSERT ON articlesTable
BEGIN
INSERT INTO articlesTable ( articleId, articleIsLiked)
VALUES(NEW.articleId, 1) ON DUPLICATE KEY UPDATE
articleIsLiked = 0;
END;
articlesTable
id PK
articleId int
articleIsLiked int
答案 0 :(得分:0)
您无法使用触发器将INSERT更改为UPDATE。
最简单的方法是在您的代码中:
db.beginTransaction();
try {
ContentValues cv = new ContentValues();
long c = DatabaseUtils.queryNumEntries(db, "articlesTable",
"articleId = " + id);
if (c > 0) {
cv.put("articleIsLiked", 0);
db.update("articlesTable", cv, ""articleId = " + id, null);
} else {
cv.put("articleId", id);
cv.put("articleIsLiked", 1);
db.insert("articlesTable", null, cv);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}