在SQLiteDatabase上使用两个表执行select

时间:2012-04-20 10:16:40

标签: android sqlite

我正在开发Android 3.1应用程序。

我有以下表格:

FormBlock
---------
FormId  (INTEGER) FOREIGN KEY TO Form.id
BlockId (INTEGER) FOREIGN KEY TO Block.id

Block
----------
id          (INTEGER) PRIMARY KEY
name        (TEXT)    NOT NULL
orderInForm (INTEGER) NOT NULL

我想做以下选择:

SELECT block.blockId, block.name, block.orderInForm FROM Block, FormBlock WHERE FormBlock.FormId = 1 AND block.blockId = FormBlock.blockId;

如何使用SQLiteDatabase.query(...)或rawQuery()执行select语句?

2 个答案:

答案 0 :(得分:2)

SELECT 
    block.blockId, block.name, block.orderInForm
FROM
    Block, FormBlock 
WHERE
    FormBlock.FormId = 1 AND block.blockId = FormBlock.blockId;

query

String table = "Block, FormBlock";
String[] columns = new String[] { "block.blockId", "block.name", "block.orderInForm" };
String where = "FormBlock.FormId = 1 AND block.blockId = FormBlock.blockId";
Cursor result = db.query(table, columns, where, null, null, null, null);

如果1是动态的,那么

int formId = 1;
String table = "Block, FormBlock";
String[] columns = new String[] { "block.blockId", "block.name", "block.orderInForm" };
String where = "FormBlock.FormId = ? AND block.blockId = FormBlock.blockId";
String[] whereArgs = new String[] { String.valueOf(formId) };
Cursor result = db.query(table, columns, where, whereArgs, null, null, null);

答案 1 :(得分:1)

试试这个:

String query = "SELECT * FROM Block WHERE id IN
                  (SELECT BlockId FROM FormBlock WHERE FormId = 1)";

Cursor c = database.rawQuery(query, null);