MySQL subqueries with WordPress tables
A subquery is a SELECT inside another query. It answers “which rows match a condition that depends on other rows”: posts of authors who wrote more than five posts, meta rows whose post no longer exists, the average number of posts per category. Many of these could be written as JOINs too, but a subquery is often the clearer way to say what you mean.
Problem: You need posts of active authors only, a list (and cleanup) of orphaned post meta, and an average over grouped counts, each in one query.
Solution: Use IN ( SELECT ... ) for filtering by a list, NOT EXISTS ( SELECT 1 ... ) for finding rows without a match, and a subquery in FROM (a derived table) for calculations on grouped results.
The examples use the wp_ prefix; replace it with yours.
IN: posts of authors with more than five posts
SELECT ID, post_title, post_author
FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
AND post_author IN (
SELECT post_author
FROM wp_posts
WHERE post_type = 'post' AND post_status = 'publish'
GROUP BY post_author
HAVING COUNT(*) > 5
);
NOT EXISTS: orphaned post meta
When posts are deleted with SQL instead of through WordPress, their meta rows stay behind:
SELECT COUNT(*) FROM wp_postmeta pm WHERE NOT EXISTS ( SELECT 1 FROM wp_posts p WHERE p.ID = pm.post_id );
To remove them, make a backup first, then:
DELETE pm FROM wp_postmeta pm WHERE NOT EXISTS ( SELECT 1 FROM wp_posts p WHERE p.ID = pm.post_id );
NOT EXISTS is the safe choice here. NOT IN ( SELECT ID FROM wp_posts ) gives the same result only as long as the subquery returns no NULL; with a single NULL in the list, NOT IN matches nothing at all.
A derived table: averages over groups
SELECT ROUND( AVG( posts ), 1 ) AS avg_posts_per_category
FROM (
SELECT tt.term_taxonomy_id, COUNT(*) AS posts
FROM wp_term_taxonomy tt
JOIN wp_term_relationships tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.taxonomy = 'category'
GROUP BY tt.term_taxonomy_id
) AS per_category;
A derived table must have an alias (AS per_category), even if it is not used elsewhere.
A scalar subquery: a value per row
SELECT p.ID, p.post_title,
( SELECT COUNT(*) FROM wp_comments c
WHERE c.comment_post_ID = p.ID AND c.comment_approved = '1' ) AS comments
FROM wp_posts p
WHERE p.post_type = 'post' AND p.post_status = 'publish'
ORDER BY comments DESC
LIMIT 10;
In PHP
<?php
global $wpdb;
$orphans = (int) $wpdb->get_var(
"SELECT COUNT(*) FROM {$wpdb->postmeta} pm
WHERE NOT EXISTS ( SELECT 1 FROM {$wpdb->posts} p WHERE p.ID = pm.post_id )"
);
NOTE: A correlated subquery (one that refers to the outer row, like the comment count above) runs once per row of the outer query. For ten rows that is nothing; over the whole posts table of a big site it can be slow, and a JOIN with GROUP BY is usually faster. Check with EXPLAIN when a report takes more than a second.