嘿,伙计们,我有一个查询,它选择数据并组织,但顺序不对。我要做的是选择一个用户在那一周内的所有评论,并按每个主题对其进行排序,然后按每个评论在各自集群中的最新时间戳对集群进行排序。我当前的查询选择了正确的数据,但顺序似乎是随机的。有人有什么想法吗?

    select * from (
      SELECT
        topic.topic_title, topic.topic_id
      FROM comments
      JOIN topic ON topic.topic_id=comments.topic_id
      WHERE comments.user='$user' AND comments.timestamp>$week order by comments.timestamp desc) derived_table
group by topic_id

最佳答案

最终版本,我希望:

SELECT topic_title, topic_id
      FROM comments
      JOIN topic ON topic.topic_id = comments.topic_id
      WHERE comments.user = '$user' AND comments.timestamp > $week
      GROUP BY topic_id ORDER BY MAX(timestamp) DESC

MAX(时间戳)将单独应用于每个分组(请参见http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html)。

关于mysql - 使用子查询在MySQL中按多列排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2679932/

10-15 21:13