The bug I talked about a little while ago has now also had the fix I wrote committed to the mysql-trunk 5.5.6-m3 repository.
PlanetMySQL Voting: Vote UP / Vote DOWN
The bug I talked about a little while ago has now also had the fix I wrote committed to the mysql-trunk 5.5.6-m3 repository.

If your Wordpress comment counts got messed up, whether because of a plugin (I'm talking about you, DISQUS) or you messed with your database manually and did something wrong (yup, that's what I just did), fear not – I have a solution for you.
But first, a little background.
Here's how comment counts work in WP:
Fire up a MySQL shell or your favorite MySQL software (mine is Navicat) and run this query.
It assumes your database is called wordpress and the prefix is wp_, so adjust those accordingly.
1 2 3 4 5 6 7 8 | SELECT wpp.id, wpp.post_title, wpp.comment_count, wpc.cnt
FROM wordpress.wp_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM wordpress.wp_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
WHERE wpp.post_type IN ('post', 'page')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL)); |
The result of this query is a list of posts whose comment_counts differ from the actual number of comments associated with each of them.
The left count is the cached number, while the right one is the right one.
The following query will recalculate and fix the comment counts for all posts that are out of sync (ones we just queried for above):
1 2 3 4 5 6 7 8 | UPDATE wordpress.wp_posts wpp
LEFT JOIN
(SELECT comment_post_id AS c_post_id, count(*) AS cnt FROM wordpress.wp_comments
WHERE comment_approved = 1 GROUP BY comment_post_id) wpc
ON wpp.id=wpc.c_post_id
SET wpp.comment_count=wpc.cnt
WHERE wpp.post_type IN ('post', 'page')
AND (wpp.comment_count!=wpc.cnt OR (wpp.comment_count != 0 AND wpc.cnt IS NULL)); |
I tested this approach on a few test cases but if you experience any problems, please do alert me in the comments and desribe your problem.
Happy WP hacking!
On Friday afternoon, I went to give a presentation about MySQL advanced features at the Sardegna Ricerche technology park. The presentation included a quick introduction to MySQL Sandbox, something that I have been doing for years, and I thought I could do blindfold, if required. However, something didn't go as expected. |