我正在为我的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 :(得分: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。虽然它们有效,但它们会提供最差的性能。
答案 1 :(得分: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
答案 2 :(得分: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