How to db_select DISTINCT on a particular field in Drupal 7? I understand that you can specify ->distinct() on the db_select statement so that it only returns distinct values when looking at ALL fields. But what I want is to return distinct values by only looking at ONE field. Here's my code:

$event_table = db_select('my_table', 'e')
    -&gt;distinct()
    -&gt;orderBy('e.time', 'ASC');//ORDER BY
$event_table-&gt;join('node', 'n', 'e.nid = n.nid'); //JOIN node with events
$event_table-&gt;groupBy('e.time');//GROUP BY time
$event_table-&gt;fields('e')//SELECT the fields from events
    -&gt;fields('n',array('type','status','title'))//SELECT the fields from node
    -&gt;orderBy('e.time', 'ASC');//ORDER BY

$result_event_table = $event_table-&gt;execute();
$result_event_table = $result_event_table-&gt;fetchAllAssoc('time');


Suppose I want the distinct column to be e.nid. You'd think  ->distinct('e.nid') would work but it still returns distinct values based on all fields (i.e. distinct(columns1, column2, column3, etc).
Assuming you're trying to get to roughly this query:

SELECT DISTINCT e.nid AS nid, e.time AS time, n.type AS type, n.status AS status, n.title AS title
FROM 
{my_table} e
INNER JOIN {node} n ON n.nid = e.nid
GROUP BY e.time
ORDER BY e.time ASC


You would use:

$query = db_select('my_table', 'e')
  -&gt;distinct()
  -&gt;fields('e', array('nid', 'time', 'foo', 'bar'))
  -&gt;fields('n', array('type', 'status', 'title'))
  -&gt;groupBy('e.time')
  -&gt;orderBy('e.time');

$query-&gt;join('node', 'n', 'n.nid = e.nid');