2009-09-01 72 views
1

我在爲我的WordPress博客建立一個「作者」頁面,列出所有當前網站貢獻者以及各種其他信息,例如發佈的帖子數量,最後發表的日期等尋找作者的最新職位

谷歌和Wordpress Codex指出我在MySQL中使用子查詢來在一個查詢中提取我需要的所有數據,並且它對於獲取每個作者發佈的帖子數量非常有用。

我無法工作的是找到每個作者的最新帖子的帖子ID。

說,工程沒有最新的帖子目前查詢:

SELECT users.ID, (SELECT count(*) FROM posts, users WHERE users.ID = posts.post_author AND posts.post_type = 'post' AND posts.post_status = 'publish') AS post_count FROM users ORDER BY post_count DESC 

我試圖得到最新帖子ID爲每個作者( 'latest_post_ID'):

SELECT users.ID, (SELECT count(*) FROM posts, users WHERE users.ID = posts.post_author AND posts.post_type = 'post' AND posts.post_status = 'publish') AS post_count, (SELECT posts.ID FROM posts, users WHERE users.ID = posts.post_author AND posts.post_type = 'post' AND posts.post_status = 'publish' ORDER BY posts.post_date DESC LIMIT 1) AS latest_post_ID FROM users ORDER BY post_count DESC 

的問題是與加子查詢 - 查詢將查找任何與任何作者匹配發布的帖子,而不是我想要的('users.ID = posts.post_author')。

我非常感謝它,如果有人用一些SQL-fu可以指出我濫用和/或濫用MySQL子查詢的地方。

+0

您缺少的鏈接正在綁定您最初選擇的用戶標識和子查詢。 – 2009-09-01 05:52:37

回答

2

試試這個。

SELECT a.ID, 

(SELECT count(*) 
FROM posts 
WHERE a.ID = posts.post_author 
AND posts.post_type = 'post' 
AND posts.post_status = 'publish') AS post_count, 

(SELECT posts.ID 
FROM posts 
WHERE a.ID = posts.post_author 
AND posts.post_type = 'post' 
AND posts.post_status = 'publish' 
ORDER BY posts.post_date DESC LIMIT 1) AS latest_post_ID 

FROM users As a 
ORDER BY post_count DESC 
+0

這在我的WP 2.8上按預期工作。 – 2009-09-01 05:52:05

+0

謝謝,這個作品! – bouchard 2009-09-01 06:20:22

0

下面的查詢應該在MySQL的工作:

SELECT posts.ID FROM posts, 
(SELECT MAX(posts.post_date) AS max_date, 
posts.post_author AS author 

FROM posts 

WHERE users.ID = posts.post_author 

GROUP BY posts.post_author) AS max_date_table 

WHERE posts.post_date = max_date_table.max_date AND 
posts.post_author = max_date_table.author 
+0

您在最外面的SELECT子句中缺少post_count和latest_post_id。 – 2009-09-01 06:00:59

3
SELECT u.id, 
     COUNT(*) AS post_count, 
     MAX(p.id) AS latest_post_id 
    FROM POSTS p 
    JOIN USERS u ON u.ID = p.post_author 
    WHERE p.post_type = 'post' 
    AND p.post_status = 'publish' 
GROUP BY u.id 
ORDER BY post_count DESC 

我不建議在SELECT子句中使用SELECTS的。雖然他們工作,他們將提供最差的表現。

+0

帖子ID不一定表示最新帖子。如果有人創建了新文章,但僅在其他文章發佈後發佈,則最終的錯誤帖子將爲「最新」。你應該從post_date檢查它。 – 2012-08-27 14:17:58