Search code examples
sqliteandroid-sqlitegroup-concat

Android Sqlite Multiple Joins with Alias does not return anything


I have this query:

 Cursor res = db.rawQuery("SELECT t1.Id, t2.EmpId FROM table1 t1 
                              LEFT JOIN table2 t2 ON t1.t2Id = t2.Id
                              LEFT JOIN table3 t3 ON t1.t3Id = t3.Id
                           WHERE t1.Id = 90909", null);

Now when I go

if(res.moveToFirst()){
   do{
        MyObject obj = new MyObject();
        obj.Id = res.getInt(res.getColumnIndex("t1.Id"));

        MyObjectAsProperty objProp = new MyObjectAsProperty();
        objProp.EmpId = res.getInt(res.getColumnIndex("t2.EmpId"));
   }while(res.moveToNext());
}

The objProp.EmpId returns nothing (or 0). I looked at the cursor columns and it's Fields basically did not include the table alias names. How do I go about getting the values of those aliased fields?

Thanks!

EDIT

Apologies. I forgot to add that if for example it's referencing the same other table multiple times with the same field.

Here's updated query

Cursor res = db.rawQuery("SELECT t1.Id, t2.EmpId, t2b.EmpId FROM table1 t1 
                                  LEFT JOIN table2 t2 ON t1.t2Id = t2.Id
                                  LEFT JOIN table2 t2b ON t1.t2bId = t2b.Id
                               WHERE t1.Id = 90909", null);

if(res.moveToFirst()){
       do{
            MyObject obj = new MyObject();
            obj.Id = res.getInt(res.getColumnIndex("t1.Id"));

            MyObjectAsProperty objProp = new MyObjectAsProperty();
            objProp.EmpId = res.getInt(res.getColumnIndex("t2.EmpId"));

            MyObjectAsProperty objProp2 = new MyObjectAsProperty();
            objProp2 .EmpId = res.getInt(res.getColumnIndex("t2bId.EmpId"));
       }while(res.moveToNext());
    }

Solution

  • The documentation says:

    The name of a result column is the value of the "AS" clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified and may change from one release of SQLite to the next.

    So you must use AS:

    SELECT t1.Id AS ObjID, t2.EmpId AS EmpId, ...