tags:

views:

181

answers:

1

I have a table, tableA that I want to resort and then insert / update each resulting row into tableB. Currently I have something like this:

delete from tableB; set @place = 0; INSERT INTO tableB (id, place, name, colD, colF) SELECT (id, greatest(@place := @place + 1, 0) from tableA order by colD desc;

This works, but I don't want to delete from tableB each time as the table will likely contain hundred of thousands of rows. So, I wanted to use ON DUPLICATE KEY UPDATE as each id column is set as a PRIMARY KEY. I have tried various versions of the following (moving the ON DUPLICATE KEY UPDATE clause around)

INSERT INTO tableB (id, place, name, colD, colF) SELECT (id, greatest(@place := @place + 1, 0) from tableA order by colD desc ON DUPLICATE KEY UPDATE tableB.place = @place, tableB.name = tableA.name, tableB.colD = tableA.colD, tableB.colF = tableA.colF;

NO LUCK,

Any pointers on how to do this?

+1  A: 

Why don't you use views for this purpose?

create view tableb as 
SELECT (id, greatest(@place := @place + 1, 0) from tableA order by colD desc;

That way will have less problems because it will be automatically updated.

MySQL documentation

Bogdan Gusiev