背景
最近在自己的后台项目中
为了方便展示好友消息列表数据
发现,对于最新聊天记录的获取还挺麻烦的
用到了至少我这几乎没用过的 UNION 语句,在此整理一番 …
首先,鄙人的对话记录表设计字段如下:
各字段意义一目了然,可作为参考
整理得到的 SQL语句,使用时可替换其中的 当前用户ID 即可
为了便于阅读,缩进如下:
代码语言:javascript复制
SELECT count(is_read = 0 or null) AS count_no_read,friend_id,uni_table.content,log_time,type,user_name,picture
FROM (
SELECT to_id as friend_id,content,1 as is_read,log_time,type
FROM tp5_xchat_logs WHERE (from_id = 1) AND (to_id <> 1)
UNION
SELECT from_id as friend_id,content,is_read,log_time,type
FROM tp5_xchat_logs WHERE (from_id <> 1) AND (to_id = 1)
ORDER BY log_time desc
)AS uni_table
INNER JOIN tp5_xadmins a on friend_id = a.id GROUP BY friend_id ORDER BY log_time DESC;