sqlite中的嵌套语句 [英] Nested statements in sqlite
问题描述
我使用c ++中的sqlite3库从* .sqlite文件查询数据库。你可以在sqlite3中写一个查询语句like:
I'm using the sqlite3 library in c++ to query the database from *.sqlite file. can you write a query statement in sqlite3 like:
char* sql = "select name from table id = (select full_name from second_table where column = 4);"
第二个语句应该返回一个id以使用第一个语句完成查询语句。
The second statement should return an id to complete the query statement with first statement.
推荐答案
是的,只要确保嵌套查询不会返回多个行。将LIMIT 1添加到嵌套查询的末尾以解决此问题。还要确保它总是返回一行,否则主查询将不起作用。
Yes you can, just make sure that the nested query doesn't return more than one row. Add a LIMIT 1 to the end of the nested query to fix this. Also make sure that it always returns a row, or else the main query will not work.
如果要在嵌套查询中匹配多行,则可以使用 IN
,如下所示:
If you want to match several rows in the nested query, then you can use either IN
, like so:
char* sql = "select name from table WHERE id IN (select full_name from second_table where column = 4);"
或者您可以使用 JOIN
:
or you can use JOIN
:
char* sql = "select name from table JOIN second_table ON table.id = second_table.full_name WHERE second_table.column = 4"
请注意, IN
方法可能非常慢, JOIN
可以非常快速,如果您在右边的列上建立索引
Note that the IN
method can be very slow, and that JOIN
can be very fast, if you index on the right columns
这篇关于sqlite中的嵌套语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!