views:

62

answers:

1

I'm trying to get my head around with the group by command, basically I'm trying to select all messages of a user, group them by subject then show them - just like how face book does it.

The result should have the latest message id, the sender's id, the date, and the total count of the messages in that subject.

The message table can look like the following:

message
-------
id
sender_id
subject
created_at

So the result should show all user's messages grouped by the same subject.

+1  A: 
SELECT sender_ID, subject, MAX(id), MAX(created_at), COUNT (id) 
FROM message 
WHERE recipient_id = current_user_id OR sender_id = current_user_id
GROUP BY subject, sender_ID, receipient_id
ORDER BY MAX(created_at) DESC

With GROUP BY, anything that isn't in the GROUP BY clause needs to be in an aggregate funtion (e.g. COUNT, SUM, MAX, etc) in the SELECT statement.

EDIT - realised the Group By above doesn't quite do what I think you want (altho example result set would help), so one thought to simplify this. At the time of message creation are you able to set an additional column value - conversation_id. This would be assigned to a new value when a new message is created and then reused for any replies. You could then Group By conversation_id to group the messages together in the way that I think you'd like them to be

Kris C
You might want to "order by sender_ID subject"
TheSteve0
good point, updated
Kris C
guys, sorting by sender id will not list the messages from latest to oldest...? it needs to be sorted by created_at so it will show the messages by date order no?
David
okay this is a little more difficult than I thought. In my question, I did not mention to fetch only all the messages for a specific user, so there is no where clause. If we include the where clause on the sql like this: "where recipient_id = current_user_id OR sender_id = current_user_id" then the result will ALSO fetch those SAME subject but DIFFERENT user who had messaged the current user. any idea?
David
Add current_user_id to the group by too
Kris C
Thanks so much for helping. But current_user_id is a variable. so the where looks like: "WHERE recipient_id = #{current_user_id} OR sender_id = #{current_user_id}". Won't be able to put that in the group by clause.
David