left join alle主题仅限粘贴和最后发布DESC的最后发布顺序

时间:2018-01-01 14:10:52

标签: php mysql left-join

我正在尝试根据论坛ID获取所有主题。 这些主题需要先粘贴,然后按最后发布日期排序。

我有这个查询,工作得很好,但它没有以我想要的方式订购主题。

SELECT 
    forum_posts.posted_by, 
    forum_posts.posted, 
    forum_topics.id, 
    forum_topics.subject, 
    forum_topics.sticky, 
    forum_topics.closed 
FROM 
    forum_posts 
LEFT JOIN 
    forum_topics 
ON 
    forum_topics.id=forum_posts.topic_id 
WHERE forum_topics.forum_id=$forumdata->id 
GROUP BY forum_topics.id 
ORDER BY forum_posts.posted DESC

2 个答案:

答案 0 :(得分:1)

如果我正确地阅读了您的问题,那么您只需要对ORDER BY条款稍作修改:

ORDER BY
    forum_topics.sticky,          -- just add this
    forum_posts.posted DESC;

但是,当您选择非聚合列时,我的预感是您应该使用子查询来找出最新的帖子:

SELECT
    ft.*, fp1.*
FROM forum_posts fp1
INNER JOIN
(
    SELECT topic_id, MAX(posted) AS max_posted
    FROM forum_posts
    GROUP BY topic_id
) fp2
    ON fp1.topic_id = fp2.topic_id AND
       fp1.posted = fp2.max_posted
LEFT JOIN forum_topics ft
    ON fp1.id = ft.topic_id
ORDER BY
    ft.sticky;

答案 1 :(得分:0)

如果您需要先粘贴然后发帖,那么您需要通过orum_topics.sticky,forum_posts.posted订购,例如:

  SELECT 
      forum_posts.posted_by, 
      forum_posts.posted, 
      forum_topics.id, 
      forum_topics.subject, 
      forum_topics.sticky, 
      forum_topics.closed 
  FROM 
      forum_posts 
  LEFT JOIN 
      forum_topics 
  ON 
      forum_topics.id=forum_posts.topic_id 
  WHERE forum_topics.forum_id=$forumdata->id 
  GROUP BY forum_topics.id 
  ORDER BY forum_topics.sticky DESC, forum_posts.posted DESC