Answer the question
In order to leave comments, you need to log in
How to get the total number of unread messages for a conversation?
SELECT du.* FROM (
SELECT
DISTINCT ON(du."dialogId") du."dialogId",
SUBSTRING(dm."message", 1, 60),
du."joinedDateTime",
users."avatarUrl",
users.username
FROM dialogs_users du
LEFT JOIN dialogs_messages dm ON dm."dialogId" = du."dialogId"
LEFT JOIN users on users.id = dm."senderUserId"
WHERE
du."userId" = '69e56a68-edbd-4f8b-8ccd-cb8031c5c865'
AND
dm.id NOT IN (
SELECT dmd."messageId" FROM dialogs_messages_deleted dmd
WHERE dmd."userId" = '69e56a68-edbd-4f8b-8ccd-cb8031c5c865'
)
ORDER BY du."dialogId", dm."message" DESC
) du
ORDER BY du."joinedDateTime" DESC;
Answer the question
In order to leave comments, you need to log in
You have a dialogId in the final selection. With it, you make a subquery in select-e to get a single value.
SELECT du.*, (
SELECT COUNT(dm."receiverRead") "unreadMessages"
FROM dialogs_messages dm
WHERE
dm."dialogId" = du."dialogId"
AND dm."receiverRead" = false
AND dm."senderUserId" NOT IN ('69e56a68-edbd-4f8b-8ccd-cb8031c5c865')
AND dm.id NOT IN (
SELECT dmd."messageId" FROM dialogs_messages_deleted dmd
WHERE dmd."userId" = '69e56a68-edbd-4f8b-8ccd-cb8031c5c865'
)
GROUP BY dm."receiverRead"
)
FROM (
SELECT
DISTINCT ON (du."dialogId") du."dialogId",
SUBSTRING(dm."message", 1, 60),
du."joinedDateTime",
users."avatarUrl",
users.username
FROM dialogs_users du
LEFT JOIN dialogs_messages dm ON dm."dialogId" = du."dialogId"
LEFT JOIN users on users.id = dm."senderUserId"
WHERE
du."userId" = '69e56a68-edbd-4f8b-8ccd-cb8031c5c865'
AND dm.id NOT IN (
SELECT dmd."messageId" FROM dialogs_messages_deleted dmd
WHERE dmd."userId" = '69e56a68-edbd-4f8b-8ccd-cb8031c5c865'
)
ORDER BY du."dialogId", dm."message" DESC
) du
ORDER BY du."joinedDateTime" DESC;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question