Index: includes/database.mysql.inc
===================================================================
--- includes/database.mysql.inc	(revision 1391)
+++ 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)) {
+    $select = preg_replace(
+      '/((?:^|,)\s*)(?<!DISTINCT\()(?:' .$table . '\.)?' . $field . '(\s*(?:,|$))/is',
+      '\1'.$field_to_select.'\2', $matches[1], 1
+    );
+    
+    return 'SELECT'.$select.'FROM'.$matches[2];
+  }
+  return $query;
 }
 
 /**
Index: includes/database.mysqli.inc
===================================================================
--- includes/database.mysqli.inc	(revision 1391)
+++ 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)) {
+    $select = preg_replace(
+      '/((?:^|,)\s*)(?<!DISTINCT\()(?:' .$table . '\.)?' . $field . '(\s*(?:,|$))/is',
+      '\1'.$field_to_select.'\2', $matches[1], 1
+    );
+    
+    return 'SELECT'.$select.'FROM'.$matches[2];
+  }
+  return $query;
 }
 
 /**
