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

これは、投稿ごとに 1 つの日付のみを想定しています。そうでない場合、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 に答える