tags:

views:

45

answers:

4

I am trying to create a conversations based messaging system.

I want to group all messages that have the same conversation_id so that when I display a list of current conversations you only see the latest message from each conversation.

Can I group the values in the mysql query, or would I have to do it in the php?

A: 

You can group that in mysql query something like t this:

select * from table where conversation_id = id_here

This will get all the records that have conversation_id set to id_here and then you can use php to work on that array/group.

Sarfraz
Hi Sarfraz, Thanks but I need to retrieve all conversations which will all have different id's so couldn't specify the exact id
Ben
@Ben: Then i think you probably need to use the GROUP BY keyword of sql.
Sarfraz
Thanks, yeah I am getting somewhere now with this.SELECT messages . * , messages_conversations.subject FROM messages, messages_conversations WHERE messages.to_user_id = '".$userid."' GROUP BY messages.conversation_id
Ben
A: 

Its a basic example of parent child relation in database. each message much have unique id and iys should also refer to the parent key of convo id.

then you can get the latest message for a given convo id.

I have a table called messages_convos that has fields id, subject and a table called messages which has id, convos_id (id from messages_convos), from_user_id, to_user_id, message_content, date_sent, message_read
Ben
Exactly, you have done the db design correctly. I am unable to understand your problem then. Just do a select of id from message tables on the basis of timsestamp or id field( in case its auto incrementing) for a given Id on message_convo table.Select * from message m , message_convo c where c.id = m.convos_id and m.convo_id = parameter[0] order by timestamp desc limit 1.
+2  A: 
select m.convos_id, m.message_content from messages m  
          where m.id in 
          (select MAX(m1.id) from messages m1 GROUP BY m1.convos_id)
Salil
A: 

Thanks for your help, this is what I have ended with.

SELECT messages . * , messages_conversations.subject FROM messages, messages_conversations WHERE messages.to_user_id = '".$userid."' AND messages_conversations.id = messages.conversation_id GROUP BY messages.conversation_id

Ben