Sqlite - SELECT 或 INSERT 和 SELECT 在一个语句中 [英] Sqlite - SELECT or INSERT and SELECT in one statement

查看:31
本文介绍了Sqlite - SELECT 或 INSERT 和 SELECT 在一个语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免编写单独的 SQL 查询来实现以下场景:

I'm trying to avoid writing separate SQL queries to achieve the following scenario:

我有一个名为值的表:

值:

id INT (PK)
data TEXT

我想检查表中是否存在某些数据,如果存在,则返回其id,否则插入并返回其id.

I would like to check if certain data exists in the table, and if it does, return its id, otherwise insert it and return its id.

(非常)天真的方法是:

The (very) naive way would be:

select id from Values where data = "SOME_DATA";

如果 id 不为空,则取它.如果 id 为空,则:

if id is not null, take it. if id is null then:

insert into Values(data) values("SOME_DATA");

然后再次选择它以查看其 id 或使用返回的 id.

and then select it again to see its id or use the returned id.

我试图在一行中实现上述功能.我想我已经接近了,但我还没有做到:到目前为止,我得到了这个:

I am trying to make the above functionality in one line. I think I'm getting close, but I couldn't make it yet: So far I got this:

select id from Values where data=(COALESCE((select data from Values where data="SOME_DATA"), (insert into Values(data) values("SOME_DATA"));

我试图利用这样一个事实,即第二个选择将返回 null,然后将返回 COALESCE 的第二个参数.至今没有成功.我错过了什么?

I'm trying to take advantage of the fact that the second select will return null and then the second argument to COALESCE will be returned. No success so far. What am I missing?

推荐答案

您的命令不起作用,因为在 SQL 中,INSERT 不返回值.

Your command does not work because in SQL, INSERT does not return a value.

如果您在 data 列上有唯一的约束/索引,则可以使用它来防止盲目插入值时出现重复;这使用 SQLite 的 INSERT OR IGNORE 扩展:

If you have a unique constraint/index on the data column, you can use that to prevent duplicates if you blindly insert the value; this uses SQLite's INSERT OR IGNORE extension:

INSERT OR IGNORE INTO "Values"(data) VALUES('SOME_DATE');
SELECT id FROM "Values" WHERE data = 'SOME_DATA';

这篇关于Sqlite - SELECT 或 INSERT 和 SELECT 在一个语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆