gpt4 book ai didi

php - MySQL通过发送/接收的最后一条消息获取有序的联系人列表

转载 作者:行者123 更新时间:2023-11-29 07:35:55 26 4
gpt4 key购买 nike

这是我的情况,我有 2 个表,一个关于 friend ,另一个关于消息。 friend 表是这样的:

user_id|friend_id|accepted
12 | 1 | 1
13 | 1 | 1
1 | 3 | 1

接受可以是 0 或 1。(1 接受,0 不接受)

消息表

message|time    |user_id|receiver_id
hi! | 1328688| 1 | 12
hey | 1343409| 12 | 1

时间是一个时间戳,所以我需要按顺序列出 每个 friend 的最高时间戳

我需要按照最后一条消息(发送/接收)的顺序列出所有联系人(已接受 = 1)。换句话说,我需要按发送者和接收者分组,并且只从每个 friend 那里获取一个值(最后一个)。用户“12”可以在 user_id 或 friend_id 中,也可以在 user_id 和 receiver_id 中……所以我需要检查两者。

有人可以帮助我吗?谢谢 guyz!

编辑我的查询:

SELECT * FROM friends,messages
WHERE (friends.user_id='$my_id'
OR friends.friend_id ='$my_id'
AND friends.accepted='1')
AND messages.user_id='$my_id'
OR messages.receiver_id='$my_id'

GROUP BY friends.friend_id
ORDER BY messages.time DESC");

我尝试了 INNER JOIN,但这太疯狂了(我不太擅长 mysql)

编辑 2

消息表 Messages table

friend 表 Friends table

EDIT 3 $my_id 是取我的 user_id 的变量

最佳答案

已解决,这个查询对我有用

SELECT messages.* FROM messages, (SELECT MAX(id) as lastid
FROM messages
WHERE (messages.receiver_id = '$myid' OR messages.sender_id = '$myid')

GROUP BY CONCAT(LEAST(messages.receiver_id,messages.sender_id),'.',
GREATEST(messages.receiver_id, messages.sender_id))) as conversations
WHERE id = conversations.lastid
ORDER BY messages.time DESC

关于php - MySQL通过发送/接收的最后一条消息获取有序的联系人列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com