I have a MySQL database with multiple columns. Entries can appear in columns multiple times (except for the primary key). I'd like to be able to return, for each matching distinct entry in one column, the whole row containing the first appearence of that entry from the table as sorted by a second column. Consider a table like:
---------------------------------------
| id | item | cost | location | ... |
---------------------------------------
| 1 | apple | 10 | kitchen | ... |
| 2 | apple | 20 | fridge | ... |
| 3 | banana | 20 | kitchen | ... |
| 4 | carrot | 30 | fridge | ... |
| 5 | apple | 10 | barn | ... |
---------------------------------------
So, sorting by cost (then id) and selecting distinct item, I'd get back rows 1, 3 and 4. (The cheapest cost for each item.) Sorting by location (then id) and selecting distinct item, I'd get back 5, 4, 3. (The alphabetical first location for each item.)
I currently select the distinct whatevers and then for each one, order the table by the index column and select the first row it appears in, and then, when I have them all, resort that result set by the index. I could also select the whole table ordered by the index and then add a row to a local array each time I find a new whatever until I have my limit. The first requires lots of selects and the second requires reading the whole table.
Is there a better way of doing this? (I'm using MySQL 5.1.53 and PHP 5.2.11.)