I have two tables: Contacts and Messages. I'd like to fetch a Chat structure that doesn't belong to any table (in other words: there's no Chats table I just want to build a query) This query should contain:
- A
contactI'm referring to in that chat - A
lastMessagebetween me and that contact (If I don't have a last message w/ that contact - I should get no result from that contact specifically) unreadCountthat tells how many messages inside that conversation are not read yet.
My tables are:
- Contacts
uniqueId(Blob)username(Text)
- Messages
isRead(Bool)sender(Blob)receiver(Blob)timestamp(Integer)
The farthest I got was this:
WITH
"lastMessage" AS (
SELECT *, MAX("timestamp")
FROM "messages"
GROUP BY "sender", "receiver"
),
"unreadCount" AS (
SELECT COUNT(*)
FROM "messages" WHERE "isRead" = 0
GROUP BY "sender"
)
SELECT "contacts".*, "unreadCount".*, "lastMessage".*
FROM "contacts"
JOIN "lastMessage"
ON ("lastMessage"."sender" = "contacts"."uniqueId")
OR ("lastMessage"."receiver" = "contacts"."uniqueId")
LEFT JOIN "unreadCount"
ON "unreadCount"."sender" = "contacts"."uniqueId"
ORDER BY "lastMessage"."timestamp" DESC
PS: The sender/receiver of a message is equal to a contact uniqueId (or my own uniqueId and vice-versa)
The issue with the current result I'm having is that its fetching duplicate chats for each contact (considering each one of them has a sent and a received message) and its not working to fetch the un-reads
Edit 1: Here's what I'm looking for...
I have on my DB:
Contacts table:
- username: John Doe,
uniqueId: (Blob...)
- username: Alice Shrek,
uniqueId: (Blob...)
Messages table:
- sender: (Blob from my uniqueId),
receiver: (Blob from John Doe),
isRead: true,
timestamp: ...1
- sender: (Blob from John Doe),
receiver: (Blob from my uniqueId),
isRead: false,
timestamp: ...2
- sender: (Blob from my uniqueId),
receiver: (Blob from Alice Shrek),
isRead: true,
timestamp: ...3
- sender: (Blob from Alice Shrek),
receiver: (Blob from my uniqueId),
isRead: false,
timestamp: ...4
(In other words, this hypothetical scenario I have two contacts and two messages w/ each of those contacts. One message I sent which is the read one and one I received which is the unread one)
I want my query to fetch these:
- username: John Doe,
uniqueId: (Blob from John doe),
sender: (Blob from John doe)
receiver: (Blob from my uniqueId)
timestamp: ...2
unreadCount: 1
- username: Alice Shrek,
uniqueId: (Blob from Alice Shrek),
sender: (Blob from Alice Shrek)
receiver: (Blob from my uniqueId)
timestamp: ...4
unreadCount: 1
