13

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

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

I'm using SQLiteDatabase and its query() method.

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?

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
user1049280
  • 5,176
  • 8
  • 35
  • 52

2 Answers2

29

Try this:

Cursor mCursor = db.rawQuery("SELECT * FROM Table1, Table2 " +
                             "WHERE Table1.id = Table2.id_table1 " +
                             "GROUP BY Table1.data1", null);
Graham Borland
  • 60,055
  • 21
  • 138
  • 179
14

So when you need to JOIN Tables, you have to use rawQuery instead of query. So your statement

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 JOIN because it more faster and safer then your approach. So then your rawQuery method can looks like this:

cursor = db.rawQuery(SELECT_QUERY, null);

Have look at rawQuery in SQLiteDatabase

Regards

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106