SELECT
1 as message_type,
m1.id,
m1.parent,
m1.thread,
u.username AS name,
u.gid,
m1.email,
m1.subject,
m1.catid,
m1.userid,
m1.moved,
m1.topic_emoticon,
UNIX_TIMESTAMP(t.last_post_ts) AS lastpost,
m1.time AS time,
0 AS rating,
t.replies,
t.last_post_ts,
m2.userid AS last_userid,
u2.username AS last_username,
u2.gid AS last_gid
FROM
jos_sb_threads t
JOIN #__sb_messages AS m1 ON
(m1.id = t.thread_id AND m1.message_type = t.message_type)
JOIN #__users AS u ON (u.id = m1.userid)
LEFT JOIN #__sb_messages AS m2 ON
(m2.id = t.last_reply_id AND m2.message_type = t.message_type)
LEFT JOIN #__users AS u2 ON (u2.id = m2.userid)
WHERE
t.cat_id = $gid
AND t.message_type = 1
ORDER by lastpost DESC
LIMIT $offset,$threads_per_page