简体   繁体   English

如何在sqlite的SELECT语句中将INSERT用作子查询?

[英]How can i use INSERT as subquery in SELECT statement in sqlite?

I want something like this. 我想要这样的东西。 But I dont know the proper syntax. 但是我不知道正确的语法。

select id from table1
where name = (insert into table1 (name) values ('value_abcd'))

When you say: 当你说:

WHERE something = somethingElse

somethingElse is an expression (so is something , but anyway). somethingElse是一个表达式(所以是something ,但无论如何)。 You are trying to use an INSERT statement as your somethingElse , but an INSERT statement doesn't return anything, so it can not be evaluated as an expression. 您试图将INSERT语句用作somethingElse ,但是INSERT语句不返回任何内容,因此不能将其评估为表达式。 Therefore, not only is whatever you're trying to invalid syntax, it also doesn't make any sense in a pseudo-code kind of way. 因此,您不仅尝试使语法无效,而且以伪代码的方式也没有任何意义。

Perhaps if you can try to explain more clearly what it is you're trying to do (and why), someone will be able to suggest something for you. 也许,如果您可以尝试更清楚地说明您要做什么(以及原因),那么有人可以为您提供一些建议。

So you have a table with an autoincrementing primary key, and you want to know its value after you have inserted a record. 因此,您有一个带有自动递增主键的表,并且您想在插入记录后知道其值。

In SQL, you can use the last_insert_rowid function: 在SQL中,可以使用last_insert_rowid函数:

INSERT INTO table1(name) VALUES('value_abcd');
SELECT last_insert_rowid();

However, in most cases you do not need to execute a separate SELECT query because most libraries have some function to return that value. 但是,在大多数情况下,您不需要执行单独的SELECT查询,因为大多数库都有一些函数可以返回该值。 For example, SQLite's C API has the sqlite3_last_insert_rowid function, and Android's insert function returns the ID directly. 例如,SQLite的C API具有sqlite3_last_insert_rowid函数,而Android的insert函数则直接返回ID。

If id column of the table is set as identity, then in SQL 如果将表的id列设置为标识,则在SQL中

insert into table1(name) value('name')
select SCOPE_IDENTITY()

It will return last auto generated idetity value 它将返回上一次自动生成的理想值

If id column is not set as identity then in SQL 如果未将id列设置为标识,则在SQL中

insert into table1(name)
output inserted.id
value('name')

It will return all id values inserted in a single statement. 它将返回插入到单个语句中的所有id值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM