Reputation: 3
Trying to build a somewhat complicated WordPress query. In one query, I'm trying to:
Here is my original query:
SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name ORDER BY date DESC;
This query returns all authors even those with 9 or less published posts.
Here is the query with the count for the posts:
SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name ORDER BY date DESC;
In this query you can see that I've added:
COUNT(post_date) as post_count
Which returns everything beautifully.
It's only when I add this WHERE clause, does the query break
post_count > 9
I get this error message:
Unknown column 'post_count' in 'where clause'
Any idea why this is happing? My theories:
If you could shed some light, I would greatly appreciate it.
Thanks.
Upvotes: 0
Views: 210
Reputation: 1981
You're looking for the "HAVING" operator.
SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name HAVING post_count>9 ORDER BY date DESC;
Upvotes: 1
Reputation: 3925
change the condition in the WHERE part of the query post_count > 9
with HAVING post_count > 9
after the GROUP BY
the final query will be SELECT wp_users.ID, display_name, user_url, user_email, MAX(post_date) as date, COUNT(post_date) as post_count FROM wp_users, wp_posts WHERE wp_users.ID = wp_posts.post_author AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' GROUP BY display_name HAVING post_count > 9 ORDER BY date DESC;
Upvotes: 1