Index: includes/database.mysql.inc
===================================================================
--- includes/database.mysql.inc	(revision 1119)
+++ includes/database.mysql.inc	(working copy)
@@ -362,8 +362,16 @@ function db_column_exists($table, $colum
  */
 function db_distinct_field($table, $field, $query) {
   $field_to_select = 'DISTINCT('. $table .'.'. $field .')';
-  // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
-  return preg_replace('/(SELECT.*)(?:'. $table .'\.|\s)(?<!DISTINCT\()(?<!DISTINCT\('. $table .'\.)'. $field .'(.*FROM )/AUsi', '\1 '. $field_to_select .'\2', $query);
+  $matches = array();
+  if (preg_match('/^SELECT(.*?)FROM/is', $query, $matches)) {
+    $orig = $matches[0];
+    $selection = $matches[1];
+    if (!preg_match('/DISTINCT\((' . $table .'\.)?' . $field . '/is', $selection)) {
+      $new = preg_replace('/((^|,)\s*)(' . $table .'\.)?' . $field . '/is', '\1'.$field_to_select, $selection);
+      return str_replace($orig, 'SELECT' . $new . 'FROM', $query);
+    }
+  }
+  return $query;
 }
 
 /**
Index: includes/database.mysqli.inc
===================================================================
--- includes/database.mysqli.inc	(revision 1119)
+++ includes/database.mysqli.inc	(working copy)
@@ -364,8 +364,16 @@ function db_column_exists($table, $colum
  */
 function db_distinct_field($table, $field, $query) {
   $field_to_select = 'DISTINCT('. $table .'.'. $field .')';
-  // (?<!text) is a negative look-behind (no need to rewrite queries that already use DISTINCT).
-  return preg_replace('/(SELECT.*)(?:'. $table .'\.|\s)(?<!DISTINCT\()(?<!DISTINCT\('. $table .'\.)'. $field .'(.*FROM )/AUsi', '\1 '. $field_to_select .'\2', $query);
+  $matches = array();
+  if (preg_match('/^SELECT(.*?)FROM/is', $query, $matches)) {
+    $orig = $matches[0];
+    $selection = $matches[1];
+    if (!preg_match('/DISTINCT\((' . $table .'\.)?' . $field . '/is', $selection)) {
+      $new = preg_replace('/((^|,)\s*)(' . $table .'\.)?' . $field . '/is', '\1'.$field_to_select, $selection);
+      return str_replace($orig, 'SELECT' . $new . 'FROM', $query);
+    }
+  }
+  return $query;
 }
 
 /**
