用于在中间行中插入新行的MySQL语法?

时间:2011-06-13 16:57:19

标签: mysql insert

mysql sintax用于在中间行或我们想要的任何地方插入新行而不更新现有行,但会自动增加主键(id)?

' id | value
' 1  | 100
' 2  | 200
' 3  | 400
' 4  | 500

我想在id 2之后插入一个新行,值为300.我想要输出如下:

' id | value
' 1  | 100
' 2  | 200
' 3  | 300  <-- new row with id (automatic increment)
' 4  | 400  <-- id=id+1
' 5  | 500  <-- id=id+1 

感谢。

4 个答案:

答案 0 :(得分:33)

您必须将其拆分为2个操作。

START TRANSACTION;

UPDATE table1 SET id = id + 1 WHERE id >= 3 order by id DESC;

INSERT INTO table1 (id, value) VALUES (3, 300);

COMMIT;

请注意,您需要更新语句中的order by,因此它将首先以最高ID开头。

另一个想法是将id声明为decimal(10,1),并将值2.5作为ID插入2到3之间。

答案 1 :(得分:0)

insert into my_table (value)
values (select value+100 from my_table order by id desc limit 1)

答案 2 :(得分:0)

您不能将自动增量功能用于新行。下一个自动增量值将始终在生成的最后一个自动增量值之后;永远不是中间价值。我看到这样做的唯一方法是相当痛苦的:插入一个新行,该行是最后一行的副本(以缓冲表的自动增量数),然后更新所有剩余行(包括您认为的那一行)新的)。

如果值是唯一的,我想知道使用单独的id列的智慧。为什么不将value列作为主键?

答案 3 :(得分:0)

PostgreSQL 在当前行后插入新行 (python)

例如当前行的 id 为 6,我需要插入 id 为 7 的新行

lastIdString = "select max(id) from sheet2_Spare_SFPs;"
lastIdQuery = cursor.execute(lastIdString);
lastIdResult = cursor.fetchone()
lastId = lastIdResult[0]
futureOrder = currentrow_id + 1
newUpdateMax = 2 + currentrow_id

# first step move all rows that bigger than target new id eg : 
# new value should be in 6 any thing > 6 moved starting from max id
# this will make the id after the current row empty

temporarySquence1 = "create temporary sequence IF NOT EXISTS seq_upd;"
temporarySquence01 = "select setval('seq_upd', (select max(id) from sheet2_Spare_SFPs) + %s);"%newUpdateMax
temporarySquence001 = "update sheet2_Spare_SFPs set id=nextval('seq_upd') where id>%s;"%currentrow_id
cursor.execute(temporarySquence1)
cursor.execute(temporarySquence01)
cursor.execute(temporarySquence001)

# insert new value after current row eg 7 set the id as futrue id which is current + 1

insertTheNewRow = "INSERT INTO sheet2_Spare_SFPs (id, PID) VALUES (%s, 'hi');"%futureOrder
cursor.execute(insertTheNewRow)
# last step back the group to the new sequence any item > futre id
temporarySquence2 = "create temporary sequence IF NOT EXISTS seq_two;"
temporarySquence02 = "select setval('seq_two', %s, false);"%newUpdateMax
temporarySquence002 = "update sheet2_Spare_SFPs set id=nextval('seq_two') where id>%s;"%futureOrder

cursor.execute(temporarySquence2)
cursor.execute(temporarySquence02)
cursor.execute(temporarySquence002)