diff --git a/wp-includes/template-functions-links.php b/wp-includes/template-functions-links.php
index b4e3493718..498f0444dd 100644
--- a/wp-includes/template-functions-links.php
+++ b/wp-includes/template-functions-links.php
@@ -437,9 +437,9 @@ function next_posts_link($label='Next Page »', $max_page=0) {
 			if ( isset($max_num_pages) ) {
 				$max_page = $max_num_pages;
 			} else {
-        preg_match('#FROM (.*) GROUP BY#', $request, $matches);
+        preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);
         $fromwhere = $matches[1];
-        $numposts = $wpdb->get_var("SELECT COUNT(ID) FROM $fromwhere");
+        $numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
         $max_page = $max_num_pages = ceil($numposts / $posts_per_page);
 			}
     }
@@ -479,9 +479,9 @@ function posts_nav_link($sep=' — ', $prelabel='« Previous Page', $nx
 
 		if (get_query_var('what_to_show') == 'posts') {
 			if ( ! isset($max_num_pages) ) {
-				preg_match('#FROM (.*) GROUP BY#', $request, $matches);
+				preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);
 				$fromwhere = $matches[1];
-				$numposts = $wpdb->get_var("SELECT COUNT(ID) FROM $fromwhere");
+				$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
 				$max_num_pages = ceil($numposts / $posts_per_page);
 			}
 		} else {