Вопрос

I have a table with an auto increment ID that runs a lot of INSERTs and DELETEs resulting in big gaps in the numbers. I'm just wondering for the sake of neatness, is there a query that will start with the lowest ID, assign it 1 and work up +1 from there? The ID is not in a relation with any other column in the database.

So it would go from, e.g:

1034 2572 9012

to:

1 2 3

I don't want to reset the auto increment, I know how to do that. I was to actually change the IDs. Or is this considered bad practice?

Thanks.

Это было полезно?

Решение 2

Although it is not a good practice you could use a query like this:

Let's assume we have a table with two fiels id and value where id is of type INT.

insert into table (id, value)
select max(id)+1, 'value' from table

Be aware that with a lot of insert/update there could be problems if more than one queries runs simultaneously.

Другие советы

I'd consider it as bad practice. But however ... you could select your data into a second table having another autoincrement key activated, but without your id and then truncate your current table and reinsert your data together with new id... Of course, there is a danger of loosing data etc. and I really wouldn't do it.

P.S. And you will need to reset the current value of your serial too.

SET @id = 0;
UPDATE tbl_config SET id = @id := @id + 1 ORDER BY id;
SET @alt = CONCAT('ALTER TABLE tbl_config AUTO_INCREMENT = ', @id + 1);
PREPARE aifix FROM @alt;
EXECUTE aifix;
DEALLOCATE PREPARE aifix;

Please note that: if you use ids as reference from external keys you'll came into a big problem of breaking data coherency !

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top