我有一个要求,我必须根据未读消息,然后是最新的对话,从聊天表中订购用户。
我的表格结构如下:
id | from_member_id | to_member_id | added_time |消息| is_viewed
这里from_member_id和to_member_id是成员表的主键。 message是发送给对方的消息,is_vied是一个标志,表示接收者或to_member_id是否查看了消息。所以,我有一个member_id现在我必须将它与两列匹配,但我希望结果应该根据未读消息先排序,然后是未读消息。
我正在使用此查询
SELECT `from_member_id`
, `to_member_id`
, MAX(`added_time`) AS latest
, `is_viewed`
FROM `wp_doc_profile_message`
WHERE `from_member_id` = 3
GROUP BY `from_member_id`
ORDER BY `is_viewed` ASC, `latest` DESC
它没有给出我渴望的结果。请帮忙。
答案 0 :(得分:0)
在这里,您可以将to_member_id
与OR运算符和group by id
消息表ID匹配,以便记录不会重复
SELECT `from_member_id`,`to_member_id`,max(added_time) as latest,`is_viewed` FROM
wp_doc_profile_message WHERE from_member_id = 3 OR to_member_id=3
group by `id`
ORDER BY is_viewed ASC, latest DESC
OR
SELECT pm.`from_member_id`,pm.`to_member_id`,max(pm.added_time) as latest,pm.`is_viewed` FROM
wp_doc_profile_message pm
LEFT JOIN members m ON (m.id=pm.`from_member_id` OR m.id=pm.`to_member_id` )
group by pm.`id`
ORDER BY pm.is_viewed ASC, latest DESC