Search code examples
androidsqlitecursor

SQLite query 2 tables into android cursor


I have 2 tables i SQLite working with Android.

Table 1 = T1

_id = INTEGER PRIMARY KEY AUTOINCREMENT
name = TEXT NOT NULL
time = TEXT NOT NULL

Table 2 = T2

_id = INTEGER PRIMARY KEY AUTOINCREMENT
ref = TEXT NOT NULL
info = TEXT NOT NULL

IN QUERY This is a list from T1 and works fine

String orderBy =  DBhelper.time + " ASC";
String[] columns = new String[]{ DBhelper._id, DBhelper.name, DBhelper.time};
Cursor c = db.query(true, DBhelper.T1, columns, null, null, null, null, orderBy, null, null);

Now I want to add in a lookup to table 2 in the query, like old fashioned:

SELECT T1._id, T1.name, T1.time, T2.info FROM T1, T2 WHERE T2.ref = T1._id;

Mind you: T1._id is integer and T2.ref is string.

Can anyone help me to do this?


Solution

  • When you're starting with a raw SQL query, the easiest way to use it is with rawQuery:

    String sql = "SELECT T1._id, T1.name, T1.time, T2.info FROM T1 JOIN T2 ON T2.ref = T1._id";
    Cursor c = db.rawQuery(sql, null);
    

    The not-so-easy way would be to use SQLiteQueryBuilder, but this is useful mostly for content providers that need to safely handle SQL snippets from potentially malicious third party apps.