简体   繁体   English

将auto_increment值添加到具有现有数据的表中

[英]Add auto_increment value to table with existing data

I have a table with around 400 rows in it on phpmyadmin. 我在phpmyadmin上有一个约有400行的表。 I have added an id column and it is the primary key and is an auto increment. 我添加了一个id列,它是主键,并且是自动递增的。 How can I update the table with sql and add a value for each row in the id column without ? 如何使用sql更新表并为id列中的每一行添加一个值而没有? I was trying to do it with something like 我试图用类似的东西

WHILE (SELECT COUNT(*) FROM cong WHERE 'ID' IS NULL) > 0
BEGIN
    SET ROWCOUNT 1
    UPDATE cong SET 'ID' = MAX('ID')+1
END

but that comes back with an error: 但是返回一个错误:

 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE (SELECT COUNT(*) FROM cong WHERE 'ID' IS NULL) > 0 BEGIN SET ROWCOUN' at line 1

How can I achieve adding the auto increment number into each row? 如何实现将自动递增编号添加到每一行?

If I understand correctly, you originally did not have the id column, inserted the ~400 rows, and then decided you needed an id and added the column, setting it as a primary key and auto_increment. 如果我理解正确,您最初没有id列,插入了约400行,然后决定需要一个id并添加了该列,将其设置为主键和auto_increment。 Now you want to go back and add values to each of the ~400 rows which did not previously have an ID. 现在,您想返回并将值添加到〜400行中以前没有ID的每行中。

When you added the primary key and auto_increment, it should have created those auto_increment values for you. 添加主键和auto_increment时,它应该已经为您创建了这些auto_increment值。 I just did a test with several rows of data (a single varchar column), then through phpMyAdmin (since you tagged your post with phpmyadmin) I added a new column id of type INT, checking the A_I (auto_increment) checkbox and selecting PRIMARY as the key. 我只是用几行数据进行了测试(一个varchar列),然后通过phpMyAdmin(因为您用phpmyadmin标记了帖子),我添加了一个新的INT类型的列ID,检查了A_I(auto_increment)复选框并选择PRIMARY作为钥匙。 Browsing the data shows that my existing rows each have an ID. 浏览数据表明我的现有行都有一个ID。

Are you saying your column is a primary key with auto_increment set and the field is blank? 您是说您的列是设置了auto_increment的主键,并且该字段为空白吗? It doesn't make sense that MySQL would allow that. MySQL不允许这样做是没有意义的。 If that's true, can you post your table structure? 如果是这样,您可以发布表格结构吗?

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

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