Question

Here is my sql fiddle.

http://sqlfiddle.com/#!2/7f0780/1/0

I seem to have a problem that when I group two columns to get the max() value it returns the wrong associated data.

You will see the id's are incorrect.

Could someone please help me.

create table table1 (id int,id1 int, id2 int, version int);
insert into table1 values 
(1,7,9,1),
(2,7,9,2),
(3,7,9,3),
(4,7,9,4),
(5,9,7,5),
(6,9,7,6);


SELECT  max(version),id
      FROM    table1
      group BY
              id1,id2



MAX(VERSION)    ID
4               1
6               5
Was it helpful?

Solution

Your SQL Query is:

SELECT  max(version), id
FROM    table1
group BY id1, id2

Note that you are grouping by two columns. But, you are selecting neither of them in the select statement. Instead, you have id. The value of id comes from an arbitrary row, as explained in the MySQL documentation. My advice is to never use this extension, unless you really, really understand what you are doing.

If you want the id associated with the maximum value, you can do it using not exists:

select *
from table1 t
where not exists (select 1
                  from table1 t1
                  where t1.id1 = t.id1 and
                        t1.id2 = t.id2 and
                        t1.version > t.version
                 );

That is, select all rows from table1 where the version for the id1/id2 pair has no larger value.

EDIT:

I should add that for performance reasons, an index on table1(id1, id2, version) will help this query a lot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top