Log in

View Full Version : SQL Select only first unique row



CCH
01-29-2010, 10:43 AM
I'm trying to build a query for mySQL to pull information from a database, but my issue is that I want to pull only the first unique value using a specific field as the index.
The problem is, when I used the DISTINCT/GROUP BY trick, it returns the last unique value instead.

For example in the following database:
[ ID | Info ]
[ 10 | Data 1 ]
[ 10 | Data 2 ]
[ 12 | Data 3 ]

The output I want will be:
[ ID | Info ]
[ 10 | Data 1 ]
[ 12 | Data 3 ]

But instead I get:
[ ID | Info ]
[ 10 | Data 2 ]
[ 12 | Data 3 ]

djr33
01-29-2010, 01:42 PM
Without testing this to be sure, I believe you can always use ORDER BY `table` ASC (ascending) or DESC (descending) to specify the order.

So based on your explanation, try:
..... ORDER BY `table` DESC

(because ASC is usually the default-- if that returns the same results, switch to ASC)

Alternatively you could of course just get all results, order by ASC/DESC as desired and remove duplicates with PHP:
while ($row = mysql_fetch_assoc($queryresult)) {
$output[$row['id']] = $row['info'];
}
That's not quite as efficient, but if you only have a few duplicates and not that much data overall it would be fine.