我有一个问题。
我有一个这样的数据库:
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是与之聊天的人的身份证。
希望你们能帮忙:)。
答案 0 :(得分:1)
感谢所有回复。真的很赞成它,但我已经把它弄清楚了;)
现在我得到了以下内容:
$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);
答案 1 :(得分:0)
几年前我遇到了这样的问题。我这样做了:
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
答案 2 :(得分:0)
试试这个:(假设每个字段必须包含Auto-increment_from
或to
。对于收到的案例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