我正在尝试一个代码我自己的论坛系统,一切都很顺利,除了一件事。
在浏览类别时,我如何能够检索每个线程的创建者的用户名,还能够检索在每个帖子中发布最后帖子的用户的用户名?
这是我到目前为止所做的,但我仍然只检索1个用户名(OP的用户名)。
SELECT
c_name, <-- category name
t_title, <-- thread title
t_by, <-- thread started by user id
username, <-- username of the thread starter
p_by, <-- post by user id
p_date, <-- post posted date
COUNT(p_id) as total_posts
FROM
forum_categories
LEFT JOIN
forum_threads
ON
t_cat = c_id
LEFT JOIN
forum_posts
ON
p_thread = t_id
LEFT JOIN
users
ON
t_by = id
AND
p_by = id
WHERE
t_cat = 1
如您所见,我只检索线程启动器的用户名。 甚至可以使用单个查询来执行此操作吗?
由于
答案 0 :(得分:1)
您应该在查询中为两个用户保持联接:
SELECT
c_name, <-- category name
t_title, <-- thread title
t_by, <-- thread started by user id
ut_by.username, <-- username of the thread starter
p_by, <-- post by user id
up_by.username, <-- username of the post
p_date, <-- post posted date
COUNT(p_id) as total_posts
FROM
forum_categories
LEFT JOIN
forum_threads
ON t_cat = c_id
LEFT JOIN
forum_posts
ON p_thread = t_id
LEFT JOIN
users ut_by
ON t_by = ut_by.id
LEFT JOIN
users up_by
on p_by = up_by.id
WHERE
t_cat = 1
这是关于获取两者的用户详细信息的答案。关于此查询可能包含的其他错误的免责声明。