检索子类别的最新主题

I am trying to retrieve the latest topic of an subcategory. Here is my SQL:

    SELECT * FROM threads
LEFT JOIN subs 
ON subs.category_id = threads.subcategory_id
LEFT JOIN categories 
ON categories.id = subs.category_id
INNER JOIN (
    SELECT id, MAX(lastdate) lastdate
    FROM threads
    GROUP BY id
) b ON subs.category_id = threads.subcategory_id AND threads.lastdate = b.lastdate
GROUP BY subs.category_id, threads.subcategory_id, threads.lastdate DESC

However, if I am trying to make an thread with an subcategory which links to an category which is used twice, it doesn't work.

Maybe someone can help me out.

Subs in database: http://dl1.joxi.net/drive/2016/08/01/0017/1178/1131674/74/78baa81e01.png(as you can see, some of the subcategories has the same category_id

Updated query. It now duplicate the echo output for each new category linked to an category which is used twice: http://joxi.ru/DmBJzQ5c1Ll0mP