tags:

views:

60

answers:

1

I have a transaction table like so

id , name , code  ,  flag 
1 ,  john , 1234-3,   2
2 ,  joe  , 1111-2,   1
3 ,  paul , 1234-3,   3
4 ,  asdf , 1234-3,   3
5 ,  asdf , 1111-2,   5
6 ,  asdf , 1234-3,   8

Basically, what I want to do is get the last instance of a code check the flag and update all previous flags with the same code with the last flag num.

So in in the case of code 1234-3 it should update all flags with that code with flag num 8 in the case of 1111-2, it needs to update all flags with that code with 5.

I want to transform it into this table

id , name , code  ,  flag 
1 ,  john , 1234-3,   8
2 ,  joe  , 1111-2,   5
3 ,  paul , 1234-3,   8
4 ,  asdf , 1234-3,   8
5 ,  asdf , 1111-2,   5
6 ,  asdf , 1234-3,   8

I'd like to do this in MySQL purely if possible. There is a very large set of data.

+4  A: 
UPDATE  t_transaction tu
JOIN    (
        SELECT  tm.code, tm.flag
        FROM    (
                SELECT  code, MAX(id) AS id
                FROM    t_transaction
                GROUP BY
                        code
                ) td
        JOIN    t_transaction tm
        ON      tm.id = td.id
        ) t
ON      tu.code = t.code
SET     tu.flag = t.flag

Make sure you have an index on (code), if your table is InnoDB and id is a PRIMARY KEY, or on (code, id) if your table is MyISAM or id is not a PRIMARY KEY.

This index will be used both both for JOIN's and for efficient GROUP BY.

To set the value to the MAX(flag) (not the last flag):

UPDATE  t_transaction tu
JOIN    (
        SELECT  code, MAX(flag) AS flag
        FROM    t_transaction
        GROUP BY
                code
        ) t
ON      tu.code = t.code
SET     tu.flag = t.flag
Quassnoi
intersting, just to understand what your doing; Are you joining the table to itself?
Derek Organ
@Derek: thrice .
Quassnoi
would it be a good idea when doing an update like this to have indices to speed up the query? 2 million rows
Derek Organ
@Derek: sure it would, see post update
Quassnoi
wow, this took me quite awhile to get it! the inner most select to get last/max id, 2nd to get the flag, 3rd to set flag by join with code. something like that
iceangel89
cheers @Quassnoi... that worked perfectly on 100k rows.. the 2million row table may take a long time but very nicely done!any thoughts on this one: http://short.ie/i9estp
Derek Organ
@Derek: see my answer there.
Quassnoi
@Quassnoi If on the above one, I wanted to set it to the max code instead of the code in that is the last instance. how would i do that?
Derek Organ
@Derek: max flag you mean?
Quassnoi