In a wordpress database, I want to select all published articles from authors who have written at least five articles, and replace the authors' IDs with their login names. I accomplished that with a selection of all published posts, filtering that two times with a JOIN
statement, one of them joining the result set of a subquery to get those authors with more than five articles.
Here we go with the code:
SELECT posts.post_author, users.user_login, posts.post_content, posts.post_date
FROM zwzt_wp.zwzt_wp_posts AS posts
INNER JOIN zwzt_wp.zwzt_wp_users AS users
ON posts.post_author=users.id
INNER JOIN (
SELECT posts1.post_author, COUNT(*) AS count
FROM zwzt_wp.zwzt_wp_posts AS posts1
WHERE posts1.post_type='post' AND posts1.post_status='publish'
GROUP BY posts1.post_author
HAVING count > 5
ORDER BY posts1.post_author
) as regular_users
ON posts.post_author=regular_users.post_author
WHERE posts.post_type='post' AND posts.post_status='publish'
ORDER BY posts.post_author, posts.post_date DESC;
To me this looks kinda bloated and time intensive to run, especially since I run two select queries on posts
. Is there any way to accomplish this in a more efficient way?
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `zwzt_wp_posts` ADD INDEX `zwzt_posts_idx_post_type_post_statu_post_autho` (`post_type`,`post_status`,`post_author`);
ALTER TABLE `zwzt_wp_users` ADD INDEX `zwzt_users_idx_id` (`id`);
SELECT
posts.post_author,
users.user_login,
posts.post_content,
posts.post_date
FROM
zwzt_wp.zwzt_wp_posts AS posts
INNER JOIN
zwzt_wp.zwzt_wp_users AS users
ON posts.post_author = users.id
INNER JOIN
(
SELECT
posts1.post_author,
COUNT(*) AS count
FROM
zwzt_wp.zwzt_wp_posts AS posts1
WHERE
posts1.post_type = 'post'
AND posts1.post_status = 'publish'
GROUP BY
posts1.post_author
HAVING
count > 5
ORDER BY
posts1.post_author
) AS regular_users
ON posts.post_author = regular_users.post_author
WHERE
posts.post_type = 'post'
AND posts.post_status = 'publish'
ORDER BY
posts.post_author,
posts.post_date DESC