【发布时间】:2011-04-17 22:11:17
【问题描述】:
在我的留言簿中,我有 2 张桌子:messages 和 replies。
现在,我想获取按 id 分组的所有消息(意味着消息和相应的回复将被分组/在一起)并按日期 DESC 排序(最新消息将排在第一位;如果消息是最旧的,但相应的回复是所有消息中的最新消息,该组将位于表格顶部),而回复将按日期 ASC 排序(最旧的回复在顶部)。
这里我的 mysql 查询效果很好,只是它没有按日期 ASC 对回复进行排序
SELECT msg.id as id, msg.comment, msg.date_added as date_added, 0 as is_reply
FROM messages AS msg
UNION
SELECT reply.msg_id as id, reply.comment, reply.date_added as date_added, 1 as is_reply
FROM pg_reply as reply
GROUP BY id
ORDER BY date_added DESC, is_reply ASC
is_reply ASC 没有按照我的设想完成工作
reply.msg_id 指定回复父级的 id (messages.id)
结果应该是什么样子>
- message A
- oldest reply B
- old reply C
- new reply Z // this is the newest message in the guestbook
- newer message E // is newer than A but older than the newest message in the guestbook, which is Z
- reply F // (this reply is newer than all messages but message Z)
【问题讨论】:
-
回复如何与他们的父消息相关联?即,您如何知道回复正在回复什么消息?我没有看到任何包含此映射的字段。
-
您使用哪个字段来链接消息及其回复?回复是否有 origmsg_id 字段?
-
@squawknull @Johan 哦,我忘了,reply.msg_id 是回复的父级
标签: mysql