3

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.)

Ben Williams
  • 6,027
  • 2
  • 30
  • 54
  • to be honest ... can you include your expected results? – ajreal Jun 17 '11 at 14:17
  • In databases the order in which rows are held in a table is considered irrelevant, as the order can (and often does) change as rows are inserted, updated, deleted, etc. If you need them in a particular order, then you need to specify what that order is with an ORDER BY clause. – GordonM Jun 17 '11 at 14:48

1 Answers1

0

If I understand it well, your problem is the famous group-wise maximum in SQL. It has already been asked on StackOverflow, for instance here

There's also a dedicated page for this in the MySQL manual, as well as many blog posts, like this high-level post.

Community
  • 1
  • 1