简体   繁体   中英

How to delete and insert serial-num in MYSQL and also reorder serial-num?

===============
| id   | name |
===============
|    1 | Ali  |
|    2 | ahmd |
|    3 | jada |
|    4 | nisr |
|    5 | sara |
|    6 | mona |
|    7 | dana |
===============

I want to re-order ID when I delete any row like id=5 and be like that =>

===============
| id   | name |
===============
|    1 | Ali  |
|    2 | ahmd |
|    3 | jada |
|    4 | nisr |
|    5 | mona |
|    6 | dana |
===============

also the same this if I insert a row with id=2 name=yafa, how to re-order the table without duplicate any value and to be like that

    | id   | name |
    ===============
    |    1 | Ali  |
    |    2 | yafa |
    |    3 | ahmd |
    |    4 | jada |
    |    5 | nisr |
    |    6 | sara |
    |    7 | mona |
    |    8 | dana |
    ===============

This is assuming you always know what 'id' you are adding or deleting. (Also, you always work with only one row at a time).

For a delete:

DELETE FROM tableName WHERE id = 5;

UPDATE tableName 
SET    id = id-1
WHERE  id > 5;

For an insert:

UPDATE tableName 
SET    id = id + 1
WHERE  id >= 2;

INSERT INTO tableName (id, name) VALUES (2, 'yafa');

Btw, why would you want to do this. Set the column 'id' to be an auto-increment field and let the database deal with it. Do you care if you are skipping numbers ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM