Advertisement
Guest User

Untitled

a guest
Apr 18th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 0.97 KB | None | 0 0
  1. SELECT *
  2. FROM forum_category AS c
  3.   LEFT JOIN (
  4. SELECT category_id, title,
  5.       (
  6.         CASE WHEN t.timestamp > MostRecentThreadSubquery.LatestReply THEN t.user_id ELSE MostRecentThreadSubquery.user_id END
  7.       ) as MostRecentUserID,
  8.       (
  9.         CASE WHEN t.timestamp > MostRecentThreadSubquery.LatestReply THEN t.timestamp ELSE MostRecentThreadSubquery.LatestReply END
  10.       ) as MostRecentTimestamp, num_replies
  11.     FROM forum_threads AS t
  12.       LEFT JOIN (
  13.         SELECT thread_id, user_id, timestamp as LatestReply, (SELECT COUNT(*) FROM forum_replies WHERE thread_id=r1.thread_id) AS num_replies
  14.         FROM forum_replies r1
  15.         WHERE timestamp = (
  16.             SELECT MAX(timestamp)
  17.             FROM forum_replies r2
  18.             WHERE r1.thread_id = r2.thread_id
  19.           )
  20.         GROUP BY thread_id
  21.       ) AS MostRecentThreadSubquery ON t.id = MostRecentThreadSubquery.thread_id
  22.   ) AS MostRecentPerThread ON c.id = MostRecentPerThread.category_id
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement