mysql组并排序UNION
|
在我的留言簿中,我有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(id5ѭ)
结果应该是什么样的>
- 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)
没有找到相关结果
已邀请:
4 个回复
脾萌
假设
是一个自动递增字段,并且较新的id也具有较ѭ9的时间戳,则此方法有效。 原始代码备注 在原始代码中
在
ASC上隐式排序;接下来的
优先于that9 and,第二orders15ѭ。 但是,如果
是
,那么两个帖子具有相同时间的机会就很少(尤其是对于答复,写它们要花一些时间), 因此,几乎不使用二阶子句。 仅当您在
中具有聚合函数时才使用
,例如
或
如果要从选择项中删除重复项,请不要使用分组依据,请使用distinct22中的distinct
摊揉售
号拳藐孔妇
藕挝