Can I perform this Android query with ContentResolver.query()? (LEFT JOIN and CASE)

后端 未结 3 848
南方客
南方客 2020-12-02 23:20

I am looking to perform the following query (in pseudo-code) on Android:

SELECT C.ID, C.NAME, CASE ISNULL(G.GROUPID,0) = 0 THEN 0 ELSE 1 END INGROUP
FROM CO         


        
相关标签:
3条回答
  • 2020-12-03 00:02

    Nope, you can't do that kind of queries with the ContentResolver.query() method. You will need to write something like this:

    SQLiteDatabase db = YourActivity.getDbHelper().getReadableDatabase();
    String query = yourLongQuery;
    Cursor c = db.rawQuery(query, null);
    YourActivity.startManagingCursor(c);
    c.setNotificationUri(YourActivity.getContentResolver(), YourContentProvider.CONTENT_URI);
    
    0 讨论(0)
  • 2020-12-03 00:05

    Edit: Okay, so this doesn't actually solve the question asked, because eidylon is tied to an existing ContentProvider as mentioned in their question. However, this does cover how you do a JOIN if you own the ContentProvider source and API. So I'll leave it for those who want to know how to handle that case.


    This is easy! But unintuitive... :)

    query(Uri uri, String[] projection, String selection, 
    String[] selectionArgs, String sortOrder)
    

    Okay, so what is URI? Typically, you have one URI per table.

    content://com.example.coolapp.contacts serves data out of your CONTACTS table. content://com.example.coolapp.groupmembers serves data out of your GROUPMEMBERSHIP table.

    But URI is really just a string. Use it however you like. Make a block of code in your ContentProvider that responds to content://com.example.coolapp.contacts_in_group. Within that block of code in the ContentProvider, you can get raw access to your SQLite DB, unfettered by the limited query() data model. Feel free to use it!

    Define your selection fields however you like. They don't have to map to table column names -- map them how you need to, in order to get your parameters in.

    Define your projection how you need -- It may contain columns from both tables after the join.

    Bing, you're done. Google does this same model internally in their own code -- Go look at the Contacts provider API -- you see "bla.RawContact" and "bla.Contact" and etc as content URIs. Each serves data out of the same table in the DB -- the different URIs just provide different views of that same table!

    0 讨论(0)
  • 2020-12-03 00:16

    You can't do that because ContentResolver has only one query method:

        query(Uri uri, String[] projection, String selection, 
    String[] selectionArgs, String sortOrder)
    

    there's no parameter for tables or FROM clauses.

    0 讨论(0)
提交回复
热议问题