简体   繁体   English

如何在MYSQL中删除并插入序列号并重新排序序列号?

[英]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 = 5之类的任何行时重新排序ID,就像这样=>

===============
| 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 = 2 name = yafa的行,也是如此,如何在不重复任何值的情况下重新排序表,就像这样

    | 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. 这是假设您始终知道要添加或删除的“ id”。 (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. 将列“ id”设置为自动递增字段,并由数据库处理。 Do you care if you are skipping numbers ? 您是否要跳过数字?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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