3

我有这样的事情:

ID | post_author | post_date | ... | post_title | post_status | ... | post_type
-------------------------------------------------------------------------------
1  | 1           | 2007-08-11| ... | A          | publish     | ... | post
2  | 3           | 2007-08-12| ... | B          | publish     | ... | post
3  | 1           | 2007-08-12| ... | C          | publish     | ... | post
4  | 1           | 2007-08-13| ... | D          | publish     | ... | post
5  | 3           | 2007-08-13| ... | E          | publish     | ... | post

我喜欢做的是按用户获取帖子数量以及最后一个帖子的标题和 ID。根据以上数据,结果应该是:

AuthorID | TotalPosts | PostID | PostTitle
------------------------------------------
1        | 3          | 5      | E
3        | 2          | 4      | D

我试过的是这样的:

SELECT 
    p1.post_author         AS  Author,
    count(p1.post_author)  AS  Posts,
    p2.post_title          AS  Title
FROM 
    wp_posts AS p1
LEFT JOIN
    wp_posts As p2
ON
    p1.ID = p2.ID
WHERE
    p1.post_type   =   'post'
AND
    p1.post_status =   'publish'
GROUP BY
    p1.post_author
ORDER BY
    Posts   DESC,
    p2.post_date   ASC
LIMIT
    2

问题是我总是得到第一篇文章的标题,而不是最后一篇文章的标题。有没有办法获得最后插入的帖子的标题?

亲切的问候

4

4 回答 4

4

如果您只想要每个作者的最新标题,您可以使用内联相关子查询。使用适当的索引,这将相对较快 - 特别是如果您只想要 2 个发表次数最多的作者的结果:

SELECT 
    post_author         AS  Author,
    COUNT(*)            AS  Posts,
    ( SELECT   p2.post_title
      FROM     wp_posts AS p2
      WHERE    p2.post_author = p1.post_author
        AND    p2.post_type = 'post'
        AND    p2.post_status = 'publish' 
      ORDER BY p2.post_date DESC
        LIMIT 1
    )                   AS  Title
FROM 
    wp_posts AS p1
WHERE
    post_type   =   'post'
AND
    post_status =   'publish'
GROUP BY
    post_author
ORDER BY
    Posts   DESC
LIMIT
    2 ;
于 2013-02-12T15:49:08.613 回答
2

像这样的东西应该工作:

SELECT p.post_author, p3.id, p3.post_title, COUNT(DISTINCT p.id) PostCount
FROM wp_posts p
   JOIN (
    SELECT Max(Post_Date) max_post_date, post_author
    FROM wp_posts
    GROUP BY post_author) p2
     ON p.post_author = p2.post_author
   JOIN wp_posts p3 on p.post_author = p3.post_author
    AND p2.max_post_date = p3.post_date
GROUP BY p.post_author, p3.id, p3.post_title

这假设每个帖子只有一个日期。如果不是,您的 ID 字段也是您的最大字段吗?

于 2013-02-12T15:45:50.807 回答
1

您能否检查此选项是否更快:

SELECT t1.*, t2.post_title FROM
    (SELECT 
        post_author         AS  Author,
        COUNT(*)            AS  Posts,
        Max(ID) AS MaxID
    FROM 
        wp_posts AS p
    WHERE
        post_type   =   'post' AND
        post_status =   'publish'
    GROUP BY post_author
    ORDER BY Posts   DESC
    LIMIT 2) t1 LEFT JOIN wp_posts t2 
                 ON t1.MaxID= t2.ID
于 2013-02-12T17:11:33.143 回答
0
ORDER BY
p2.post_date DESC,
Posts   DESC
于 2013-02-12T15:58:51.000 回答