Android 使用 SQLiteDatabase 从多个表中查询 SQLite

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11029538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:48:29  来源:igfitidea点击:

SQLite query from multiple tables using SQLiteDatabase

androidsqlite

提问by user1049280

I have 2 tables in my database, for example: Table1: id (PK), data1and Table2: id (PK), id_table1 (FK), data2. How can I make a query like that:

我的数据库中有 2 个表,例如:Table1: id (PK), data1Table2: id (PK), id_table1 (FK), data2. 我如何进行这样的查询:

SELECT * FROM Table1, Table2 WHERE Table1.id = Table2.id_table1 
GROUP BY Table1.data1

I'm using SQLiteDatabaseand its query()method.

我正在使用SQLiteDatabase它的query()方法。

Cursor mCursor = db.query(true, new String[] {"Table1","Table2"}, 
new String[] {"Table1.id","data1", "Table2.id", "id_table1", "data2"},
"Table1.id=Table2.id_table1", null, "Table1.data1", null,null,null);

But there's a problem with the second arg - it's only possible to use String, not String[] (like new String[] {"Table1","Table2}). What should I do to make a query from multiple tables in that way?

但是第二个 arg 存在问题 - 只能使用 String,而不能使用 String[](如new String[] {"Table1","Table2})。我应该怎么做才能以这种方式从多个表中进行查询?

回答by Graham Borland

Try this:

尝试这个:

Cursor mCursor = db.rawQuery("SELECT * FROM Table1, Table2 " +
                             "WHERE Table1.id = Table2.id_table1 " +
                             "GROUP BY Table1.data1", null);

回答by Simon Dorociak

So when you need to JOINTables, you have to use rawQueryinstead of query. So your statement

所以当你需要JOINTables 时,你必须使用rawQuery而不是query. 所以你的说法

String SELECT_QUERY = SELECT * FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id GROUP BY t1.data1;

I recommend to you use JOINbecause it more faster and safer then your approach. So then your rawQuerymethod can looks like this:

我建议您使用JOIN它,因为它比您的方法更快、更安全。那么你的rawQuery方法可以是这样的:

cursor = db.rawQuery(SELECT_QUERY, null);

Have look at rawQuery in SQLiteDatabase

查看SQLiteDatabase中的 rawQuery

Regards

问候