简体   繁体   中英

Need MySQL query for messages function showing newest messages (sent or received) first, grouped by user

I'm trying to make the Conversations Overview page for a messaging system in PHP/MySQL. Basically, it would look like the iPhone's Text/SMS overview page. Messages grouped by the other users you have sent or received messages from. It should show the Conversations with the newest messages (sent or received) first (descending order)

messages table

id | sender_id | receiver_id | datetime | message

Tricky problem. Try the following solution

SELECT id,sender_id,receiver_id,
CASE WHEN sender_id >= receiver_id THEN 
  CONCAT(CAST(sender_id AS CHAR),'|', CAST(receiver_id AS CHAR))
ELSE
  CONCAT(CAST(receiver_id AS CHAR),'|' CAST(sender_id AS CHAR))
END AS participants ,
`datetime`,message from messages 
ORDER BY participants,`datetime`

This way you have an extra calculated field that represents the sender_id-receiver_id relation where you require that the combination of the two is an entity. Ordering by a calculated field will probably become slow at some point. You may want to consider creating an actual extra field in the table to store the participants information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM