有条件地插入并返回rowid还是0?

发布于 2025-02-12 07:48:12 字数 267 浏览 1 评论 0原文

我知道如何使用交易来执行此操作,但我想知道我是否可以在一行中进行此操作。我的实际查询更为复杂,但我不知道的部分是如何获取rowID或0,而无需重复wery子句

insert into comment
(select @text, @userid, @date)
where (select count(*) from comment where body=@text and userid=@userid) == 0
select last_insert_rowid()

I know how to do this using a transaction but I was wondering if I can do this in a single line. My actual query is more complex but the part I can't figure out is how to get the rowid or 0 without repeating the where clause

insert into comment
(select @text, @userid, @date)
where (select count(*) from comment where body=@text and userid=@userid) == 0
select last_insert_rowid()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好听的两个字的网名 2025-02-19 07:48:14

如果您的SQLite版本为3.35.0+,则可以使用 a> clause to get the rowid of the inserted row like this:

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;

The drawback is that in case of a failed插入查询什么都没有返回。
If your app can check the number of returned rows you can translate that as 0.

See the demo< /a>。

If your version of SQLite is 3.35.0+ you can use the RETURNING clause to get the rowid of the inserted row like this:

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;

The drawback is that in case of a failed insertion the query returns nothing.
If your app can check the number of returned rows you can translate that as 0.

See the demo.

暖风昔人 2025-02-19 07:48:14

什么都不做。如果没有更新,您的查询已经返回0。

last_insert_rowid document

last_insert_rowid()sql函数是围绕sqlite3_last_insert_rowid()c/c ++接口函数的包装器。

如果没有成功的插入...

Do nothing. Your query already returns 0 if there was no update.

The last_insert_rowid documentation says

The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

And the documentation for sqlite3_last_insert_rowid says

If no successful INSERTs ... have ever occurred ..., then sqlite3_last_insert_rowid(D) returns zero.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文