【问题标题】:MySQL: Select threads and posts, order by latest activity [duplicate]MySQL:选择线程和帖子,按最新活动排序[重复]
【发布时间】:2013-12-15 00:05:30
【问题描述】:

我想获取forumthreads 列表,按最新活动排序:

  • 创建线程
  • 已创建帖子

期望的输出

Thread name  | Timestamp (Thread) | Timestamp (latest post)
-----------------------------------------------------------
Thread A     | 1                  | 10                 <- old thread, newest post (newer than newest thread)
Thread C     | 3                  | -                  <- newest thread, no post
Thread B     | 2                  | 5                 

编辑/可能的解决方案:

SELECT
    t.*,
    IFNULL
    (         
        (
            SELECT p.timestamp 
              FROM posts p 
             WHERE p.thread_id = t.id 
             ORDER BY p.timestamp DESC LIMIT 1
        ),
        t.timestamp
    ) AS sorting 
FROM 
    threads t
WHERE t.forum_id = 1
ORDER BY sorting DESC

有人有性能建议吗?谢谢大家!

【问题讨论】:

  • 样本数据,期望的结果。
  • 关于该主题的快速 google 出现了以下链接:stackoverflow.com/questions/13181966/… 该帖子中似乎有两个选项作为答案提交。我不是 SQL 专家,所以我不能确定你会如何处理这个问题,你可以从他们构建查询的方式中收集一些信息。

标签: mysql sql database select join


【解决方案1】:
SELECT t.*, IFNULL(MAX(p.`timestamp`), t.`timestamp`) AS pts FROM `threads` t, `posts` p WHERE p.`thread_id` = t.`id` AND t.`forum_id`=1 ORDER BY pts DESC

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT threads.name
      , threads.timestamp
      , latest_posts.latest_timestamp
      , GREATEST(threads.timestamp,COALESCE(latest_posts.latest_timestamp,threads.timestamp)) AS sorting
    FROM threads
    LEFT JOIN 
        (SELECT thread_id, MAX(timestamp) as latest_timestamp
        FROM posts
        GROUP BY thread_id) as latest_posts
      ON threads.id = latest_posts.thread_id
    ORDER BY sorting
    

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2012-02-12
      相关资源
      最近更新 更多