0

In my application, I have a database table containing chat messages,like below.

|---------------------------------------------|
|message      | from  | to   |time
|-------------|-------|------|----------------|
|Hello        |user1  |user2 |2015-2-26 1:15PM|
|-------------|-------|------|----------------|
|Watsup       |user2  |user1 |2015-2-26 1:25PM|
|-------------|-------|------|----------------|
|Hows u?      |user3  |user1 |2015-2-26 2:15PM|
|-------------|-------|------|----------------|
|Im fine      |user1  |user3 |2015-2-26 2:35PM|
----------------------------------------------|

In my messages page I want list messages from all users. In this condition assume, "user1" as log-inned user,

Currently I am using query,

SELECT * FROM table GROUP BY from

and I am getting output as,

    |--------------------------------|
    |user2                           |
    |Hello                           |
    |--------------------------------|
    |user2                           |
    |Watsup                          |
    |--------------------------------|
    |user3                           |
    |Hows u?                         |
    |--------------------------------|
    |user3                           |
    |Im fine                         |
    |--------------------------------|

What I want is distinct rows (like all chat apps),

|--------------------------------|
|user2                           |
|Watsup                          |
|--------------------------------|
|user3                           |
|Im fine                         |
|--------------------------------|

So, how can I write a sqlite query to fetch rows like this?

Basim Sherif
  • 5,384
  • 7
  • 48
  • 90

3 Answers3

2

You can try as below with the Group By and Having clause.

     SELECT message,from
     FROM 
        table 
    GROUP BY from
    HAVING Max(time) = Time
Mahesh
  • 8,694
  • 2
  • 32
  • 53
1

You can try something like this:

SELECT * FROM table GROUP BY MIN(from, to), MAX(from, to) ORDER BY time DESC

This will not treat GROUP BY of (userA, userB) and (userB, userA) as different and combine the two, so you will get the output as you want.

You can also JOIN this with your Contacts table so that you can get all the data you need to show on the "Recent Chats" screen in one go. Try something like this:

SELECT * FROM messages m, Contacts c WHERE (m.from = c.userid OR m.to = c.userid) GROUP BY MIN(m.from, m.to), MAX(m.from, m.to) ORDER BY m.time DESC
Tanay Shah
  • 41
  • 6
0

Use DISTINCT AND ORDERBY :

SELECT DISTINCT from,message FROM table ORDER BY time DESC;
user543
  • 3,623
  • 2
  • 16
  • 14