Question

I have an SQLite table with the following structure:

create table Message (
    _id integer primary key autoincrement,
    convo_id text,
    isSender BOOLEAN,
    isRead BOOLEAN,
    message text,
    time timestamp default (strftime('%s', 'now'))
);

It stores all the messages for each friend having a unique convo_id.

I want a query to get the last message for each convo_id (or in other words, last message of each friend).

Was it helpful?

Solution

First, find out the last timestamp for each convo_id:

SELECT convo_id,
       MAX(time) AS time
FROM Message
GROUP BY convo_id

Then, use these values to filter the records of the original table:

SELECT Message.*
FROM Message
JOIN (SELECT convo_id,
             MAX(time) AS time
      FROM Message
      GROUP BY convo_id)
USING (convo_id, time)

If you have SQLite 3.7.11 or later, you can do everything in a single step:

SELECT *,
       MAX(time)
FROM Message
GROUP BY convo_id

OTHER TIPS

Something similar to this:

select convo_id,message from Message where (convo_id,_id) IN (select convo_id,max(_id) as _id from Message group by convo_id);

Might contain syntax errors. I didn't try it on my PC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top