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:
…otherwise, use:
ORDER BYis a waste of resources because it is not used in the ultimate output nor isTOPbeing usedGROUP BYwon’t work becauseMESSAGES.idis not in the list of columns