我知道如何使用事務來做到這一點,但我想知道我是否可以在一行中做到這一點。我的實際查詢更復雜,但我無法弄清楚的部分是如何在不重復 where 子句的情況下獲取 rowid 或 0
insert into comment
(select @text, @userid, @date)
where (select count(*) from comment where body=@text and userid=@userid) == 0
select last_insert_rowid()
uj5u.com熱心網友回復:
如果您的 SQLite 版本是 3.35.0 ,您可以使用該RETURNING子句來獲取rowid插入行的 ,如下所示:
WITH cte(body, userid, date) AS (SELECT @text, @userid, @date)
INSERT INTO comment (body, userid, date)
SELECT c.*
FROM cte c
WHERE NOT EXISTS (SELECT * FROM comment t WHERE (t.body, t.userid) = (c.body, c.userid))
RETURNING rowid;
缺點是如果插入失敗,查詢不會回傳任何內容。
如果您的應用可以檢查回傳的行數,您可以將其翻譯為 0。
請參閱演示。
uj5u.com熱心網友回復:
沒做什么。如果沒有更新,您的查詢已經回傳 0。
last_insert_rowid檔案說
last_insert_rowid() SQL 函式是 sqlite3_last_insert_rowid() C/C 介面函式的包裝。
sqlite3_last_insert_rowid的檔案說
如果沒有成功的 INSERT ... 發生過 ...,則 sqlite3_last_insert_rowid(D) 回傳零。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/498257.html
標籤:sql sqlite 公共表表达式 行号 sql-返回
上一篇:為什么mvncleanverify只運行surefire插件
下一篇:游標應該只選擇具有不同值的單元格
