简体   繁体   English

按时间戳对组内的行进行排序

[英]order rows within group by timestamp

I am trying to build and inbox for private messages. 我正在尝试为私人消息建立收件箱。

$sqlInbox = "
    SELECT sender, receiver, message, parent, rView
    FROM messages 
    WHERE receiver='$log_username' OR sender='$log_username' 
    GROUP BY parent 
    ORDER BY timestamp DESC";

This code orders each group by timestamp, so if user1 sends me a message after user2, user1 will be first on the list. 该代码按时间戳对每个组进行排序,因此,如果user1在user2之后向我发送消息,则user1将在列表上排在第一位。 However, the problem I am having is that the messages within each group are NOT being ordered by timestamp, so the output for a group is always the first message that user sent, when I need it to be the most recent message that user sent. 但是,我遇到的问题是,每个组内的消息都没有按时间戳排序,因此,当我需要它是用户发送的最新消息时,组的输出始终是用户发送的第一条消息。 So, I need to order the rows within the group by timestamp, as well as ordering the groups as a whole by timestamp. 因此,我需要按时间戳对组中的行进行排序,以及按时间戳对整个组进行排序。 I cannot for the life of me figure out how to do this. 我一生无法弄清楚该如何做。 Can someone help? 有人可以帮忙吗? (parent is a common ID for all messages that share two common users regardless of sender/receiver, ie, the collection of all messages between any two users). (parent是共享两个公共用户的所有邮件的公共ID,而不考虑发送者/接收者,即任何两个用户之间所有邮件的集合)。 Thanks in advance! 提前致谢!

I need coffee, so I hope I am reading your question correctly, but isn't it just a matter of adding the parent to the order by statement? 我需要咖啡,所以我希望我能正确阅读您的问题,但这不只是将parent项添加到按语句排序的问题吗?

$sqlInbox = "
    SELECT sender, receiver, message, parent, rView
    FROM messages 
    WHERE receiver='$log_username' OR sender='$log_username' 
    GROUP BY parent 
    ORDER BY parent, timestamp DESC";

And on that note, you aren't using any aggregate functions, so you probably don't even need the group by (unless you are doing something else not in the code you posted: 并请注意,您没有使用任何聚合函数,因此您可能甚至不需要分组依据(除非您在发布的代码中没有做其他事情:

$sqlInbox = "
    SELECT sender, receiver, message, parent, rView
    FROM messages 
    WHERE receiver='$log_username' OR sender='$log_username' 
    ORDER BY parent, timestamp DESC";

Lastly, if it were my own code, I would consider adding a read/unread flag to the messages and using that additionally in the order by clause: 最后,如果这是我自己的代码,我会考虑在消息中添加一个已读/未读标志,并在order by子句中另外使用该标志:

$sqlInbox = "
    SELECT sender, receiver, message, parent, rView
    FROM messages 
    WHERE receiver='$log_username' OR sender='$log_username' 
    ORDER BY readStatus, parent, timestamp DESC";

This would split the whole thing into two sections - unread messages at the top, and read messages at the bottom - with the same other ordering as before. 这会将整个内容分为两部分-顶部为未读消息,底部为已读消息-其他顺序与以前相同。

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

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