MySQL:选择主题和帖子,按最新活动排序

时间:2013-12-15 00:05:31

标签: mysql sql database select join

我想获得最新活动排序的threads forum列表:

  • 创建主题
  • 创建帖子

期望的输出

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

有没有人有表现建议?谢谢大家!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

试试这个:

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