MySQL选择组显示最新帖子

时间:2015-06-05 18:08:13

标签: php mysql wordpress

$postids = $wpdb->get_results( 
    "
    SELECT ID, post_title, post_author, max(post_date)
    FROM $wpdb->posts
    WHERE post_status = 'publish' 
          AND post_type = 'post'
    GROUP BY post_author
    ORDER BY post_date DESC
    "
);

foreach ( $postids as $postid ) 
{
    echo $postid->ID." :: ".$postid->post_title." :: ".$postid->post_author . "<br />" ;
}

我想从每个作者中选择一个最新的帖子,但上面的代码仍然选择每个作者最老的帖子。 max(post_date)似乎不起作用。有什么建议使这项工作?

1 个答案:

答案 0 :(得分:4)

首先,您需要了解每位作者最近发布的帖子的日期。

         SELECT max(post_date) post_date, post_author
           FROM $wpdb->posts
          WHERE post_status = 'publish' 
           AND post_type = 'post'
         GROUP BY post_author

然后,您需要使用此结果来提取所需帖子的详细信息。

SELECT a.ID, a.post_title, a.post_author, a.post_date
 FROM $wpdb->posts a
 JOIN (
         SELECT max(post_date) post_date, post_author
           FROM $wpdb->posts
          WHERE post_status = 'publish' 
           AND post_type = 'post'
         GROUP BY post_author
      ) b ON a.post_author = b.post_author AND a.post_date = b.post_date
 WHERE post_status = 'publish' 
   AND post_type = 'post'
 ORDER BY post_date DESC
当你正在为此目的工作时,

GROUP BY有点棘手。

注意:我还没有在WordPress环境中调试此查询。

请注意,如果作者设法同时创建两个帖子,则它们都将具有与MAX(post_date)值匹配的post_date值。在这种情况下,此查询将返回它们。