--- database.inc.1	2005-01-30 19:13:44.000000000 +0100
+++ database.inc	2005-01-30 19:11:15.000000000 +0100
@@ -209,9 +209,8 @@ function _db_rewrite_sql($query = '', $p
 
   $where = empty($where) ? '' : '('. implode(') AND (',$where).')';
   $join = empty($join) ? '' : implode(' ',$join);
-  $field = $primary_table .'.'. $primary_key;
 
-  return array($join, $where, $distinct ? 'DISTINCT('. $field .')' : $field);
+  return array($join, $where, $distinct );
 }
 
 /**
@@ -229,34 +228,43 @@ function _db_rewrite_sql($query = '', $p
  *   The original query with JOIN and WHERE statements inserted from hook_db_rewrite_sql implementations. nid is rewritten if needed.
  */
 function db_rewrite_sql($query, $primary_table = 'n', $primary_key = 'nid',  $args = array()) {
-  list($join, $where, $field_to_select) = _db_rewrite_sql($query, $primary_table, $primary_key, $args);
+  list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table, $primary_key, $args);
 
-  // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
-  $query = preg_replace('/(SELECT.*)('. $primary_table .'\.)?(?<!DISTINCT\()(?<!DISTINCT\('. $primary_table .'\.)'. $primary_key .'(.*FROM)/AUsi', '\1'. $field_to_select .'\3', $query);
-
-  $query = preg_replace('|FROM[^[:upper:]/,]+|','\0 '. $join .' ', $query);
-  if (strpos($query, 'WHERE')) {
-    $replace = 'WHERE';
-    $add = 'AND';
-  }
-  elseif (strpos($query, 'GROUP')) {
-    $replace = 'GROUP';
-    $add = 'GROUP';
-  }
-  elseif (strpos($query, 'ORDER')) {
-    $replace = 'ORDER';
-    $add = 'ORDER';
-  }
-  elseif (strpos($query, 'LIMIT')) {
-    $replace = 'LIMIT';
-    $add = 'LIMIT';
-  }
-  else {
-    $query .= ' WHERE '. $where;
-  }
-  if (isset($replace)) {
-    $query = str_replace($replace, 'WHERE  '. $where .' '. $add .' ', $query);
+  if ($distinct) {
+    $field_to_select = 'DISTINCT($primary_table .'.'. $primary_key)';
+    // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
+    $query = preg_replace('/(SELECT.*)('. $primary_table .'\.)?(?<!DISTINCT\()(?<!DISTINCT\('. $primary_table .'\.)'. $primary_key .'(.*FROM)/AUsi', '\1'. $field_to_select .'\3', $query);
+  }
+
+  if (!empty($join)) {
+    $query = preg_replace('|FROM[^[:upper:]/,]+|','\0 '. $join .' ', $query);
+  }
+
+  if (!empty($where)) {
+    if (strpos($query, 'WHERE')) {
+      $replace = 'WHERE';
+      $add = 'AND';
+    }
+    elseif (strpos($query, 'GROUP')) {
+      $replace = 'GROUP';
+      $add = 'GROUP';
+    }
+    elseif (strpos($query, 'ORDER')) {
+      $replace = 'ORDER';
+      $add = 'ORDER';
+    }
+    elseif (strpos($query, 'LIMIT')) {
+      $replace = 'LIMIT';
+      $add = 'LIMIT';
+    }
+    else {
+      $query .= ' WHERE '. $where;
+    }
+    if (isset($replace)) {
+      $query = str_replace($replace, 'WHERE  '. $where .' '. $add .' ', $query);
+    }
   }
+
   return $query;
 }
 
