获取聊天数据并按接收方和发送方id排序


Get chat data and sort by receiver and sender id

我有一个问题。

我有一个这样的数据库:

messages_id | int | Auto-increment
from | int
to | int
message | text

现在我有问题分组他们的发件人ID。我只想检索登录的用户发送或接收的消息。这并不太难。

SELECT * FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC

但现在,他们没有分组。因为不同的人可以给这个用户发消息。我真的不知道从哪里开始。

我想要这样的东西:

array(
    [5] => array(
        [0] => "message One",
        [1] => "Message two"
    ),
    [32] => array(
        [0] => "message One",
        [1] => "Message two"
    )
);

5和32是正在聊天的人的ID。

希望大家能帮上忙

感谢大家的回复。真的很感激,但是我已经自己弄明白了;)

现在我得到了以下内容:

$currentUserID = get_current_user_id();
$rows = $wpdb->get_results("SELECT * FROM `messages` WHERE `from` = '" . $currentUserID . "' OR `to` = '" . currentUserID . "' ORDER BY `messages_id` ASC");
$messages = [];
foreach($rows as $row) {
    if($row->from == $currentUserID) {
        $messages[$row->to][] .= $row->message;
    }
    else {
        $messages[$row->from][] .= $row->message;
    }
}
print_r($messages);

几年前我就遇到过这样的问题。我这样做了:

select 'In' as MessageDirection, `From` as Contact, `To` as UserId, Message 
from Messages
where `To` = 1
union
select 'Out' as MessageDirection, `To` as Contact, `From` as UserId, Message 
from Messages
where `From` = 1
order by Contact

试试这个:(假设每个字段必须有Auto-increment_fromto。对于接收到的情况,to字段值

SELECT *, if(`Auto-increment_from` = 1 , 'From' , 'From') as meaage_type 
FROM messages WHERE from = 1 OR to = 1 ORDER BY messages_id ASC