How to re-assign colunda ID again?

1

I have a table for example

| ID  | NOME |
|  2  | Ana  |
|  7  | João |
|  15 | Vera |

The ID column is ID int NOT NULL AUTO_INCREMENT,

What do I need to get?

I want the column to be

| ID  | NOME |
|  1  | Ana  |
|  2  | João |
|  3  | Vera |

I tried many examples one of them would be to use a php to re-assign to each column field.

Is there no way to do this with an SQL command?

    
asked by anonymous 26.12.2015 / 22:26

1 answer

3

If you want sequential numbering, you do not need to change IDs, just use a counter:

SELECT    @linha := @linha + 1 AS contador,
          tabela_desejada.*
FROM      (SELECT @linha := 0) AS nada,
          tabela_desejada
ORDER BY  id;

So you will have sequential numbering.

But if you really want to change the IDs, you can use the same logic by doing an UPDATE.

However, I understand that it is a bad solution, and that it will give unnecessary maintenance. The direction of the Id field is to be the Identity of the record, not a row counter. If you need a sequential counter, you should probably use a path like the one suggested above, or a separate column for it.

In any case, follow the query :

SET       @contador:=0;
UPDATE    tabela
SET       id=@contador:=@contador+1
ORDER BY  id;

and get ready to fix the DB auto-naming on a variety of occasions.

    
26.12.2015 / 22:48