0

说我有一张这样的桌子:

身份证|姓名|
----------
1 |弗雷德 |
2 |吉姆 |
3 |特蕾西 |
4 |斯泰西|

“id”是自动递增的主索引。

我想在“#2 - jim”下面添加一行。我会称这个新行为“john”。

我怎么能在“jim”下面插入“john”,所以 john 的“id”为 3,而“john”下面的所有名字的 id 都会增加 1?

例如

身份证|姓名|
----------
1 |弗雷德 |
2 |吉姆 |
3 |约翰 |
4 |特蕾西|
5 |斯泰西|

非常感谢

4

2 回答 2

2

此命令将在 jim 之后为每个人的 id 添加 +1。

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

此命令将在 jim 之后插入一行。

INSERT INTO your_table(id,name) VALUES(3,'john');

It is a very bad idea to change the primary key value. If your table has relationships with other tables, there will be consisitency issue. Let's say it is customer table and there is an order table. The above idea will make trstacy's orders will be connected to tracy and tracy's john, etc.

于 2013-02-22T04:50:34.930 回答
0

This is not how the autoincrement directive is intended to work. You would need to use UPDATE to change the row 3 to john, UPDATE to change row 4 to tracy, and INSERT to create new row 5 as stacy. This would be awful if you needed to insert a row after row 5 of a 10,000 record table.

You COULD directly change the id value but that is very bad practice.

于 2013-02-22T04:50:58.377 回答