I have the following tables:
users:
user_id
user_name
message:
message_id
thread_id
to_id
from_id
title
message_text
message_date
status
The desired result of the query I run is to list the title of the most recent message from the most recent threads a long with the thread_id and username and to sort the result by date in descending order. I’m only going to be listing about 10 to 20 results at a time most likely.
The SQL query I came up with seems to be doing this so far, but I feel like I have over complicated it and that there may be a more optimal way to write my query.
SELECT personal_messages.message_id,
personal_messages.thread_id,
personal_messages.body,
users.username
FROM users, personal_messages
WHERE message_id IN
(SELECT MAX(message_id) from personal_messages GROUP BY thread_id)
AND users.id IN
(SELECT users.id FROM users WHERE users.id = personal_messages.from_id)
ORDER BY personal_messages.message_date DESC
Also, if anyone knows a way to get the count of all the messages with the same thread_id, that would be awesome!
Any tips would be greatly appreciated!
One of the subselects could be unnecessary
Edit: Also, if anyone knows a way to get the count of all the messages with the same thread_id, that would be awesome!