0

I have table called users and for example it looks like:

  Name  ID 
  Tom    1
  Al    55 
  Kate  22

...

The problem is: the IDs are not in sequence.

I would like to give them new IDs from 1 to length of users. I would like to declare some var=1 and make UPDATE in loop and give them new ID = var, and later do var=var+1 until var <= users length

How can I do this?

Thank you very much!

2
  • 1
    Why do you think this is a 'problem'? Hint: IT ISN'T Commented Sep 16, 2016 at 23:05
  • Of course it isn't but I need to change it because I need it to make something different. I changing web app which was build a few years ago, DB and PHP code is really wrong wrote. I don't have time to rewrite everything from scratch. Commented Sep 17, 2016 at 12:57

2 Answers 2

3

Here is how you would do that in MySQL. Just run this:

set @newid=0;
update users set ID = (@newid:=@newid+1) order by ID;
Sign up to request clarification or add additional context in comments.

1 Comment

As version of "one query": update users set ID = (@newid:=@newid+1) where 0=(select @newid:=0) order by ID;
1

If the ID in the Users table is not referenced by other tables by FK, the following query can update the ID in the table to have new consecutive values:

CREATE TABLE IF NOT EXISTS tmpUsers (
  ID int not null, 
  newID int not null auto_increment primary key
) engine = mysisam;

INSERT INTO tmpUsers (ID,newID)
SELECT ID,NULL
FROM users
ORDER BY ID;

UPDATE users u INNER JOIN tmpUsers t 
ON u.ID=t.ID
SET u.ID=t.NewID;

DROP TABLE IF EXISTS tmpUsers;

Test script:

CREATE TABLE users (ID int not null, name nvarchar(128) not null);
INSERT users(ID,name)
VALUES (1,'aaa'),(4,'bbb'),(7,'ggg'),(17,'ddd');
SELECT * FROM users;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.