SELECT disc.*, exams.id as exam_id, exams.name as exam_name, m.latest_message_author_id as latest_author_id, m.latest_message_date as latest_message_date FROM linen_discussions disc join (select orig.discussion_id, orig.user_id as latest_message_author_id, orig.date as latest_message_date from linen_discussion_messages orig join (select discussion_id, max(date) as latest_date from linen_discussion_messages group by discussion_id) x on (x.discussion_id = orig.discussion_id and orig.date = x.latest_date)) m on (m.discussion_id = disc.id) join linen_exams exams on (exams.id = disc.exam_id) WHERE disc.active=1 AND (disc.group_id is null or disc.restrict_access_to_group = 0 or disc.group_id in (select group_id from linen_user_group_membership where user_id=0)) ORDER BY LIMIT 0, 10