表名诗人中有三个字段(_id,name,count)。我想检查表中是否存在诗人姓名然后更新计数字段,增量为1,否则插入一个具有给定名称和计数为1的新记录。这是我的查询。如果在表中找不到名称,则为count插入空值。虽然如果我想更新已有的记录,它仍然有效。
<!--Crypto-JS-->
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js"></script>
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/enc-base64-min.js"></script>
答案 0 :(得分:2)
insert or replace into poet (_id,Name, count) values (
(select _id from poet where Name = "SearchName"),
"SearchName",
ifnull((select count from poet where Name = "SearchName"), 0) + 1)
答案 1 :(得分:1)
不要试图聪明。 只需使用两个命令:
db.beginTransaction();
try {
db.execSQL("UPDATE poet SET count = count + 1 WHERE Name = ?",
new Object[]{ searchName });
if (DatabaseUtils.longForQuery(db, "SELECT changes()", null) == 0) {
db.execSQL("INSERT INTO poet(Name, count) VALUES(?,?)",
new Object[]{ searchName, 1 });
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}