views:

222

answers:

3

Hi,

I have the following table

Id   Value
1     3
1     12
1     67
2     7
2     99
5     30
5     33
5     4
5     87
5     12
5     1

I'd like to update it to have this table.

Id  UniqueIdBySubSet    Value
1           1             3
1           2             12
1           3             67
2           1             7
2           2             99
5           1             30
5           2             33
5           3             4
5           4             87
5           5             12
5           6             1

I found the perfect thread on SO, but it was for mssql. I use mysql 4.1.10.

The other thread can be found here: http://stackoverflow.com/questions/492375/generating-sequences-for-subsets-of-a-table.

Does anyone knows how I can do that in mysql ?

Thank you, Jean-Francois

A: 

Write a quick script to do it. It should take less than 10 lines of code in php.

Zak
A: 

I think you'll find this article useful. In short: you can't do it in exactly one query, but you can do it in two (load your data into a new table and execute an insert statement).

David Parunakian
+2  A: 
SET  @r := 0;
SET  @id := 0;
UPDATE  mytable m
SET     m.UniqueIdBySubSet = IF(@id = id, @r := @r + 1, @r := (@id := id) - id)
ORDER BY
        id, value;
Quassnoi
Hi, I've tried and test your answer, and it doesn't work. Here's the value I get for the example up there.1, 1, 31, 2, 121, 3, 672, 1, 72, 2, 995, 3, 15, 4, 45, 5, 125, 6, 305, 7, 335, 8, 87I've been working with it for about 20 minutes, but I don't seem to get it to work. The idea seems great though, I think it could work.If you have any idea, feel free to add more informations.
Jean-Francois
I've been able to make it work. But the first index is not 1 anymore, but 0.SET @r := -1;SET @id := -1;UPDATE mytable mSET m.UniqueIdBySubSet = CASEWHEN @id = 0 THEN @r := (@id := m.Id) - m.Id WHEN m.Id = @id THEN @r := @r + 1ELSE @r := (@id := m.Id) - m.IdENDORDER BY m.Id, m.Value;Thanks for the input. It was really appreciated.
Jean-Francois