0

So my database's primary key is just a column called 'id'. When i go to add a new item into the database I want it in a specific order without having to go into the DB and changing every value after it to +1 whatever it was before.

Example:

   ID
 | 1 | item1 |
 | 2 | item2 |
 | 3 | item3 |
 | 4 | item4 |

Say I want to add an item inbetween item2 and item3. To do that I would need to change item 3's id to 4 and item4's id to 5, but currently I have to go into the database and do it automatically.

How would I make it increment automatically when I INSERT a new item?

4

1 回答 1

1

您应该考虑保持 ID 不变并添加辅助列以进行排序,例如sort_order. 需要为每个插入更改父表和相关表中的所有 ID 不是一个好主意,尤其是。如果您没有正确制作的外键。

如果你这样做,它应该很容易完成:

-- Untested
START TRANSACTION;
UPDATE foo SET sort_order=sort_order+1 WHERE sort_order>=4;
INSERT INTO foo (name, sort_order) VALUES ('item', 4);
COMMIT;
于 2013-10-15T15:34:33.923 回答