简体   繁体   中英

Get last post in each category

I've got 4 tables:

 1. forums (id,forum_id,name,group_id) - there are categories and
        sub-categories
 2. topics (id,forum_id,user_id,name,dt,deleted[default - 0])
 3. posts (id,topic_id,text,edit_dt,user_id,deleted)
 4. users (id,name)

What is the best way to get main categories last posts? Or maybe add in forums table new fields - last_post_id , last_post_name , last_post_dt , and at delete, add new topic/reply update these fields?

At first, to identify your " last post " you should add a timestamp (DateTime) to your posts table.

Also, in your question, define what are categories (i presume it's the topics) and an example of your data, paired with an example of your desired output.

我在forums表中添加了字段(last_post_id,last_poster_id,last_dt),并且在插入新的/删除的/更新的帖子时,主要论坛将使用最新信息进行更新。

If the database is not really huge, and you have index in all your foreign keys and ids, you could do it dinamically without creating any new fields.

I assume that the id field in the posts table is an autoincrment. This mysql query selects the name of the last topic with some activity in each forum.

SELECT T.name FROM forums F 
JOIN topics T ON T.forum_id = F.id
JOIN posts P ON P.topic_id = T.id
GROUP BY F.id
ORDER BY P.id ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM