WP_Comment_Query meta query 'count' conflicts with 'group by'
|Reported by:||heshiming||Owned by:|
|Component:||Comments||Keywords:||needs-testing has-patch dev-feedback|
This problem relates to /wp-includes/comment.php, both 3.5.1 and trunk are affected. The following line number refers to the 3.5.1 version.
At line 195, definition of class WP_Comment_Query , a typical meta query will generate such SQL:
SELECT * FROM wp_comments INNER JOIN wp_commentmeta ON (wp_comments.comment_ID = wp_commentmeta.comment_id) WHERE ( comment_approved = '0' OR comment_approved = '1' ) AND comment_post_ID = 22 AND ( (wp_commentmeta.meta_key = 'my_flag' AND CAST(wp_commentmeta.meta_value AS CHAR) = 'my_value') ) GROUP BY wp_comments.comment_ID ORDER BY comment_date_gmt DESC
Note that at line 357, a meta query will always generate a GROUP BY clause. This works for comment rows. Say that I've got 3 comments matching this query, I'll see each of them in a row:
comment row 1, data comment row 2, data comment row 3, data
However, this query doesn't work well then $count = true. Note that by specifying $count = true, the function only changes 'SELECT *' into 'SELECT COUNT(*)'. For 3 comment result, I'm seeing something like this:
1 1 1
And you can see, because there's a 'GROUP BY' clause. And each comment has a unique ID. The result is 3 'grouped row' of comments, and each will always have count of 1.
Therefore, the result of $wpdb->get_var() will be either 1, or NULL (when nothing is matched). I believe this behavior is not by intention.
To get count working, 'GROUP BY' clause must be removed when $count is true.