diff -rup ../drupal-6.x-dev-orig/includes/database.inc ./includes/database.inc
--- ../drupal-6.x-dev-orig/includes/database.inc	2009-09-14 03:49:34.000000000 -0700
+++ ./includes/database.inc	2009-11-18 21:54:41.000000000 -0800
@@ -339,6 +339,10 @@ function db_rewrite_sql($query, $primary
       ((?P<anonymous_view>
         # Everything within this set of parentheses is named "anonymous view"
         (?:
+          \s\*\sFROM\s\(SELECT   # This is a special case for pgsql DISTINCT 
+                                 # clause subselects, that prevents the re from
+                                 # missing.
+        |
           [^()]++                   # anything not parentheses
         |
           \( (?P>anonymous_view) \)          # an open parenthesis, more "anonymous view" and finally a close parenthesis.
@@ -371,7 +375,12 @@ function db_rewrite_sql($query, $primary
     }
     if ($matches) {
       if ($pos === FALSE) {
-        $query = $first_part . $second_part .')';
+        if ($distinct && preg_match('/(.*) node/s', $second_part, $pg_matches)) {
+          $query = $first_part . $pg_matches[1] .') node';
+        }
+        else {
+          $query = $first_part . $second_part .')';
+        }
       }
       else {
         $query = $first_part . substr($second_part, 0, -$pos) .')'. substr($second_part, -$pos);
diff -rup ../drupal-6.x-dev-orig/includes/database.mysqli.inc ./includes/database.mysqli.inc
--- ../drupal-6.x-dev-orig/includes/database.mysqli.inc	2009-07-21 01:52:30.000000000 -0700
+++ ./includes/database.mysqli.inc	2009-11-18 21:58:18.000000000 -0800
@@ -367,7 +367,7 @@ function db_distinct_field($table, $fiel
   $matches = array();
   if (preg_match('/^SELECT(.*?)FROM(.*)/is', $query, $matches)) {
     $select = preg_replace(
-      '/((?:^|,)\s*)(?<!DISTINCT\()(?:'. $table .'\.)?'. $field .'(\s*(?:,|$))/is',
+      '/((?:^|,|\()\s*)(?<!DISTINCT\()(?:'. $table .'\.)?'. $field .'(\s*(?:,|\sAS|\)|$))/is',
       '\1'. $field_to_select .'\2', $matches[1], 1
     );
     
diff -rup ../drupal-6.x-dev-orig/includes/database.mysql.inc ./includes/database.mysql.inc
--- ../drupal-6.x-dev-orig/includes/database.mysql.inc	2009-07-21 01:52:29.000000000 -0700
+++ ./includes/database.mysql.inc	2009-11-18 21:59:17.000000000 -0800
@@ -365,7 +365,7 @@ function db_distinct_field($table, $fiel
   $matches = array();
   if (preg_match('/^SELECT(.*?)FROM(.*)/is', $query, $matches)) {
     $select = preg_replace(
-      '/((?:^|,)\s*)(?<!DISTINCT\()(?:'. $table .'\.)?'. $field .'(\s*(?:,|$))/is',
+      '/((?:^|,|\()\s*)(?<!DISTINCT\()(?:'. $table .'\.)?'. $field .'(\s*(?:,|\sAS|\)|$))/is',
       '\1'. $field_to_select .'\2', $matches[1], 1
     );
     
diff -rup ../drupal-6.x-dev-orig/includes/database.pgsql.inc ./includes/database.pgsql.inc
--- ../drupal-6.x-dev-orig/includes/database.pgsql.inc	2009-09-14 03:49:34.000000000 -0700
+++ ./includes/database.pgsql.inc	2009-11-18 23:11:38.000000000 -0800
@@ -423,9 +423,7 @@ function db_distinct_field($table, $fiel
   && !preg_match('/DISTINCT\s+ON\s*\(\s*(' . $table . '\s*\.\s*)?' . $field . '\s*\)/si', $query)
   && !preg_match('/DISTINCT[ (]' . $field . '/si', $query)
   && preg_match('/(.*FROM\s+)(.*?\s)(\s*(WHERE|GROUP|HAVING|ORDER|LIMIT|FOR).*)/Asi', $query, $m)) {
-    $query = $m[1];
-    $query .= preg_replace('/([\{\w+\}]+)\s+(' . $table . ')\s/Usi', '(SELECT DISTINCT ON (' . $field . ') * FROM \1) \2 ', $m[2]);
-    $query .= $m[3];
+    $query = "SELECT DISTINCT ON ($table.$field) * FROM (". $query .") node ";
   }
   return $query;
 }
diff --git a/modules/system/tests/database.test b/modules/system/tests/database.test
new file mode 100644
index 0000000..3da8409
--- /dev/null
+++ b/modules/system/tests/database.test
@@ -0,0 +1,110 @@
+<?php
+// $Id:  $
+/**
+ * @file
+ * Tests for testing the database abstraction layer in Drupal 6.
+ */
+
+class DatabaseTestCase extends DrupalWebTestCase {
+  /**
+   * Implementation of getInfo().
+   */
+  public static function getInfo() {
+    return array(
+      'name' => t('Database functionality'),
+      'description' => t('Exercise the database helper functions, this not not test the database but the functions that abstract the database.'),
+      'group' => t('Database'),
+    );
+  }
+
+
+  /**
+   * Test the db_distinct_field() function.
+   *
+   * See http://drupal.org/node/284392 for more information
+   */
+  function testDbDistinctField() {
+
+    // These assertions are taken from:
+    // http://drupal.org/node/284392
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT table.field FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT table.field AS table_field FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) AS table_field FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT DISTINCT(table.field) FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT DISTINCT(table.field) AS table_field FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) AS table_field FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT table.field,table.field2 FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field),table.field2 FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT table.field AS table_field, table.field2 AS table_field2 FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) AS table_field, table.field2 AS table_field2 FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT DISTINCT(table.field),table.field2 FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field),table.field2 FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT DISTINCT(table.field) AS table_field, table.field2 AS table_field2 FROM table"),
+      'expected' => 'SELECT DISTINCT(table.field) AS table_field, table.field2 AS table_field2 FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT COUNT(table.field) FROM table"),
+      'expected' => 'SELECT COUNT(DISTINCT(table.field)) FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT COUNT(table.field) AS table_field FROM table"),
+      'expected' => 'SELECT COUNT(DISTINCT(table.field)) AS table_field FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT table.field1, COUNT(table.field), table.field2 FROM table"),
+      'expected' => 'SELECT table.field1, COUNT(DISTINCT(table.field)), table.field2 FROM table',
+    );
+
+    $assertions[] = array(
+      'input' => array("table", "field", "SELECT COUNT(DISTINCT(table.field)) FROM table"),
+      'expected' => 'SELECT COUNT(DISTINCT(table.field)) FROM table',
+    );
+
+
+    foreach ($assertions as $assert) {
+      $distinct_added = call_user_func_array('db_distinct_field', $assert['input']);
+      if (!$this->assertEqual(
+        $distinct_added,
+        $assert['expected'],
+        t('Add DISTINCT to %query', array('%query' => $assert['input'][2]))
+      )) {
+        $this->pass(t('Query was rewritten to: %query, expected query: %expected_query', array('%query' => $distinct_added, '%expected_query' => $assert['expected'])));
+      }
+    }
+
+
+
+
+
+  }
+
+
+}
