I have written an SQL query that gets unread messages but I think I can improve the code (speed and readability). The first select is for COUNT function, the second is for grouping messages according to conversation_id, and the final nested select is for selecting last messages.
Please give me suggestions. Thanks in advance.
SELECT COUNT(*) as unreaded FROM (
SELECT id
FROM (
SELECT id, conversation_id
FROM messages
WHERE to_id = ?
AND readed = 0
and NOT hide_from = ?
ORDER BY sended DESC
) AS temp_messages
GROUP BY conversation_id
) as temp_messages2
The query as-is will not work - you need to define all columns that aren't wrapped in aggregates in the GROUP BY.
It's not clear, but if you want a count of unique conversations, use:
SELECT COUNT(DISTINCT m.conversation_id) AS unread
FROM MESSAGES m
WHERE m.to_id = ?
AND m.readed = 0
AND m.hide_from != ?
...otherwise, use:
SELECT COUNT(*) AS unread
FROM MESSAGES m
WHERE m.to_id = ?
AND m.readed = 0
AND m.hide_from != ?
ORDER BY is a waste of resources because it is not used in the ultimate output nor is TOP being usedGROUP BY won't work because MESSAGES.id is not in the list of columnsIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With