简体   繁体   English

需要MySQL查询消息功能,首先显示按用户分组的最新消息(发送或接收)

[英]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. 我正在尝试为PHP / MySQL中的消息传递系统创建“对话概述”页面。 Basically, it would look like the iPhone's Text/SMS overview page. 基本上,它看起来像iPhone的Text / SMS概述页面。 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. 这样,您就有了一个额外的计算字段,该字段代表sender_id-receiver_id关系,您需要将两者的组合作为一个实体。 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. 您可能需要考虑在表中创建一个实际的额外字段来存储参与者信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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