【问题标题】:Group by and order by together in single query在单个查询中进行分组和排序
【发布时间】:2014-07-26 19:38:17
【问题描述】:

我有两个表:topicmessage

topic

topic_id
// some other not important columns here

message

message_id
topic_id
creation_date
// some other not important columns here

如您所见,每个主题可以有许多消息。

我想要获取的是:所有主题的列表(包含所有主题列)以及每个主题的消息计数,按属于主题的最新消息排序(最近消息在顶部的主题)。

这是我的尝试:

SELECT topic.*, COUNT(message.message_id)
FROM topic LEFT OUTER JOIN message ON topic.topic_id = message.topic_id
GROUP BY topic.topic_id
ORDER BY message.creation_date DESC

这显然行不通。我将不胜感激。

【问题讨论】:

  • 错误信息是什么?

标签: sql postgresql


【解决方案1】:

您的尝试不起作用的原因是GROUP BY 查询生成的列中没有message.creation_date

您可以将其添加到输出中,并在排序中使用它,如下所示:

SELECT
    topic.*
,   COUNT(message.message_id) cnt
,   MAX(message.creation_date) last_msg
FROM topic LEFT OUTER JOIN message ON topic.topic_id = message.topic_id
GROUP BY topic.topic_id
ORDER BY last_msg DESC

您应该能够在不为其定义列的情况下进行排序,如下所示:

SELECT topic.*, COUNT(message.message_id)
FROM topic LEFT OUTER JOIN message ON topic.topic_id = message.topic_id
GROUP BY topic.topic_id
ORDER BY MAX(message.creation_date) DESC

【讨论】:

    猜你喜欢
    • 2015-06-23
    • 2015-05-30
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多