微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 用于从每个用户获取最后一条消息的数据库查询(如facebook消息)

我需要在登录用户和他曾与之聊过的任何用户之间获取最后一条消息,就像facebook一样.这将像facebook.com/messages页面.
这是我到目前为止所做的

数据库

USER_TABLE
– cwid
– 名字
– 姓
– user_image_link

信息
– ID
– cwid1(发件人ID)
– cwid2(接收者ID)
– 消息(消息内容)
– messagetime(时间戳)
– userread(enum’Y”N’)`

查询
登录用户的id = 1

SELECT    
user_table.cwid,message.cwid1,message.cwid2,message.message,message.userread,MAX(message.messagetime),user_table.first_name,user_table.last_name,user_table.user_image_link   
    FROM message   
    INNER JOIN user_table   
    ON message.cwid1 = user_table.cwid   
    WHERE (cwid2="1")   
    GROUP BY cwid1   
    ORDER BY messagetime DESC   

这将返回用户从向他发送消息的所有人收到的最后消息.我还需要同样获取用户发送的所有消息,这可以通过以下方式完成:

SELECT    
user_table.cwid,user_table.user_image_link    
    FROM message    
    INNER JOIN user_table    
    ON message.cwid1 = user_table.cwid   
    WHERE (cwid1="1")    
    GROUP BY cwid2    
    ORDER BY messagetime DESC    

我需要他们两个混合不同的用户和消息时间排序就像Facebook消息.我是MysqL的新手,任何帮助非常感谢.谢谢!

最佳答案
我对它进行了更多的研究,并提出了这个问题.
– 它列出了来自最近用户的消息,他们向我发送了消息或收到了我的消息
– 它还包括来自群聊的消息,群组可以由任何人创建,群组中的任何人都可以邀请他们的朋友
– 它还包括读/未读标志,以突出显示前端未读消息.

这不是最有效或最优雅的查询,但它有效.任何改进都非常受欢迎

SELECT * 
FROM (
 SELECT * 
FROM (

SELECT * 
FROM (

SELECT users.id,'0' AS groupId,users.name,users.profilePic,messages.time,messages.message,'Y' AS unread 
FROM users
INNER JOIN messages ON messages.userId2 = users.id
WHERE messages.userId1 = '" . $userId . "'
UNION 
SELECT users.id,messages.read AS unread
FROM users
INNER JOIN messages ON messages.userId1 = users.id
WHERE messages.userId2 = '" . $userId . "'
) AS allUsers
ORDER BY TIME DESC
) AS allUseRSSorted
GROUP BY id
UNION
select * from(
SELECT '0' AS id,msgGroups.id AS groupId,msgGroups.name,msgGroups.image AS profilePic,IF(userGroupMsg.time IS NULL,userGroups.createdOn,userGroupMsg.time )   AS time,IF(userGroupMsg.message IS NULL,'',userGroupMsg.message ),'Y' AS unread
FROM msgGroups
LEFT JOIN userGroups ON msgGroups.id = userGroups.groupId
LEFT JOIN userGroupMsg ON msgGroups.id = userGroupMsg.groupId
WHERE userGroups.userId = '" . $userId . "'
ORDER BY time DESC

)AS allUseRSSorted
GROUP BY groupId

 )AS allSorted
ORDER BY TIME DESC

如果有人可以,请改进.

原文地址:https://www.jb51.cc/mysql/433105.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐