Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-writing this sql query

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
like image 624
mTuran Avatar asked May 10 '26 10:05

mTuran


1 Answers

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 != ?
  • The subqueries are unnecessary
  • The ORDER BY is a waste of resources because it is not used in the ultimate output nor is TOP being used
  • The GROUP BY won't work because MESSAGES.id is not in the list of columns
like image 52
OMG Ponies Avatar answered May 13 '26 03:05

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!