views:

20

answers:

2

I have a table like this:

id       number    otherfields
-------------------------------------------
664      48       aaa
665      49       bbb
666      55       ccc
667      48       ddd

My query groups by the number field, and I want it to pick the first (lowest) id, so that the data comes out like ccc,aaa,bbb (when ordered by number). However I'm getting ccc,ddd,bbb - in other words, it's picking row #667 instead of #664 for the number 48.

Oddly, this only happens on the live server; on localhost I get it the correct way even though the table is exactly the same (exported from localhost, imported onto server).

Is it possible to ensure that the GROUP BY clause picks the first ID?

+2  A: 

No, it is not possible in MySQL. You have to use a join.

SELECT id, number, otherfields FROM table 
  WHERE id in (SELECT min(id) FROM table GROUP BY number)
J-16 SDiZ
I get an error with that: *"#1241 - Operand should contain 1 column(s)"* - I'm guessing because the subquery returns 2 fields but you're only looking for 1 (the id).
DisgruntledGoat
Ah - just removing the number field from the sub-query appears to work. You don't specifically need it for the sub-query, do you? It does appear to be several times slower, though (0.3s as opposed to 0.001s for most queries).
DisgruntledGoat
@DisgruntledGoat - fixed, thanks. I guess jms's answer maybe faster. Haven't do any benchmark.
J-16 SDiZ
I indexed my `number` field and the performance has improved somewhat. I'm caching all pages anyway so it will only be that tiny bit slower once an hour :)
DisgruntledGoat
A: 

SQL-92 version.

SELECT 
     id, number, otherfields 
FROM 
     table t
     join (SELECT min(id) as id, number FROM table GROUP BY number) sq --subquery
       on t.id = sq.id
jms