Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a table like

id - some data
1 - ...
2 - ...
4 - ...
5 - ...
8 - ...
12 - ...

The table is really long, with thousands IDs. Look at IDs, there are "empty" numbers between of them. I want to reorder all IDs to have no empty ones.

Table should look like
1 - ...
2 - ...
3 - ...
4 - ...
etc.

How would the query look like?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
191 views
Welcome To Ask or Share your Answers For Others

1 Answer

I don't advocate re-numbering ids. The id column should be the primary key for the table, and gaps don't make a difference. If it is used for foreign key references, then you will be messing up your database.

But, you can do it as:

set @rn = 0;

update `table` t
    set t.id = (@rn := @rn + 1)
    order by t.id;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...