简体   繁体   中英

Query column for any of multiple variations of a substring in SQLite, Android

I have a data table that has one column called Threads.RECEPIENT_IDS. In that column, I can have rows like: 4,10,25,60 or 2,4,8,20 or just 4. How would I query all rows that contain a 4 or query for all instances that a row contains a 4 or 20. I thought of something like:

String queryString = "'4','%,4','4,%','%,4,%','20','%,20','20,%','%,20,%'";

I just can't figure out why this doesn't return any rows. My parameters and cursorLoader is below.

private final String[] threadsProjection = new String[] { Treads.RECIPIENT_IDS };
private final String threadsSelection = Threads.RECIPIENT_IDS + " like ?";
private final String threadsOrder = Threads.DATE + " DESC";

@Override
public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle) {

    switch (loaderID) {
    case SMS_MMS_QUERY:
        String queryString = bundle.getString(BUNDLE_QUERY_KEY);
        CursorLoader queryCursorLoader = new CursorLoader(context, conversationsUri, threadsProjection, threadsSelection, new String[]{queryString}, threadsOrder);
        return queryCursorLoader;
    default:
        return null;
    }
}

This goes back to database design, and using text field to hold a list of IDs is just very poor design. A better design here would be a separate table to hold the IDs, such as --

TABLE threads( *threadId, <info>, <info> )

and

TABLE thread_recipients( *threadId, *recipientId )

where * marks a primary key.

You would then populate both tables with your threads, and the query would be something simple, such as:

SELECT * 
  FROM threads 
 WHERE threadId IN ( SELECT threadId 
                       FROM thread_recipients
                      WHERE recipientId = ? )

There is no reliable way of doing what you are trying to do with the current schema. Even the LIKE queries will fail when you attempt to find recipientId "4" if there's a "24" or "34" etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM