0
在我的数据库驱动的应用程序中,我需要执行插入查询,其中一个或多个字段的值来自子查询。Android SQLITE使用来自子查询的值插入表
INSERT INTO语句可能看起来像下面的例子:
INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
目前我做它手动构建查询:
String MyQuery = "INSERT INTO mytable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String
SQLiteDatabase= db = getWritableDatabase();
db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
我想这样做的反而是:
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));
db.insert("MyTable", null, values);
db.close();
其中假方法ThisIsAQuery(...)是缺少的部分,东西t应该告诉查询生成器“SELECT ..”不是一个值,而是一个应该嵌入到插入语句中的查询。
有没有办法做到这一点?