Index: includes/database.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/database.inc,v
retrieving revision 1.61
diff -u -r1.61 database.inc
--- includes/database.inc	11 Dec 2006 22:58:17 -0000	1.61
+++ includes/database.inc	2 Jan 2007 23:25:37 -0000
@@ -267,34 +267,18 @@
     $query = db_distinct_field($primary_table, $primary_field, $query);
   }
 
-  if (!empty($where) || !empty($join)) {
-    if (!empty($where)) {
-      $new = " WHERE $where ";
-    }
-    $new = " $join $new";
-    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';
+  preg_match('/^(.+?)(\s+WHERE\s+(.+?))?(\s+(?:GROUP|ORDER|LIMIT).+)?$/s', $query, $match);
+  if (!empty($where)) {
+    if (!empty($match[2])) {
+      $query = "$match[1] $join WHERE ($match[3]) AND $where $match[4]";
     }
     else {
-      $query .= $new;
-    }
-    if (isset($replace)) {
-      $query = str_replace($replace, "$new $add ", $query);
+      $query = "$match[1] $join WHERE $where $match[4]";
     }
   }
+  else {
+    $query = "$match[1] $join $match[2] $match[4]";
+  }
 
   return $query;
 }
