我正在为一个Web项目的自定义论坛工作。我有id的类别,id和类别的主题,以及id和topic以及用户id的帖子。我要做的是显示类别列表,其中包含来自类别表的数据以及来自该类别中最新帖子的帖子表中的数据,该帖子的相关用户的数据,以及该主题的一些数据与最新的帖子相关联。
我一直在试图弄清楚查询问题,但是我对复杂的mysql查询没有足够的了解,知道在这里使用什么模式或技术。以下是我到目前为止的情况:
SELECT u1.*, fp1.*, ft1.*, fc1.* from forum_posts AS fp1
LEFT JOIN users AS u1 ON u1.id = fp1.post_by
LEFT JOIN forum_topics AS ft1 on ft1.id = fp1.post_topic
LEFT JOIN forum_categories AS fc1 on fc1.id = ft1.topic_cat
GROUP BY fc1.id
ORDER BY fp1.id ASC;
但这不会返回我正在寻找的结果。问题在于尝试获取每个类别的最新帖子以及该帖子的关联主题。
以下是每个表的数据库结构:
forum_categories
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| cat_name | varchar(255) | NO | UNI | NULL | |
| cat_description | varchar(500) | NO | | NULL | |
| cat_views | bigint(20) unsigned | YES | | 0 | |
| status | tinyint(1) | NO | | 1 | |
+-----------------+---------------------+------+-----+---------+----------------+
forum_topics
+---------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| topic_subject | varchar(255) | NO | | NULL | |
| topic_date | datetime | NO | | NULL | |
| topic_cat | bigint(20) unsigned | NO | MUL | NULL | |
| topic_by | bigint(20) unsigned | NO | MUL | NULL | |
| topic_views | bigint(20) unsigned | YES | | 0 | |
+---------------+---------------------+------+-----+---------+----------------+
forum_posts
+--------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| post_content | text | NO | | NULL | |
| post_date | datetime | NO | | NULL | |
| post_topic | bigint(20) unsigned | NO | MUL | NULL | |
| post_by | bigint(20) unsigned | NO | MUL | NULL | |
+--------------+---------------------+------+-----+---------+----------------+
用户
+-----------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| user_type | varchar(50) | YES | | NULL | |
| email | varchar(255) | NO | UNI | NULL | |
| username | varchar(255) | YES | UNI | NULL | |
| password | char(60) | NO | | NULL | |
| image | text | YES | | NULL | |
| status | tinyint(1) | NO | | 1 | |
+-----------+---------------------+------+-----+---------+----------------+
这是我想要实现的输出的图像。 “类别”显示来自forum_categories表的数据,“最近”下的数据显示最新帖子的用户,帖子和主题数据:
请帮帮我。谢谢。