我的实时数据库中有一个包含数千条记录的表。
今天早上跟踪一个错误,我发现表“id”列没有设置为 auto_increment,所以我有 1000 条 id = 0 的记录。
:(
mysql> explain feed_items; +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | id | int(11) | NO | | 0 | | | feed_id | int(11) | YES | MUL | NULL | | | title | varchar(255) | YES | | NULL | | | description | text | YES | | NULL | | | item_link | varchar(255) | NO | | NULL | | | item_updated | datetime | YES | | NULL | | | item_id | varchar(255) | YES | | NULL | | | created_at | datetime | YES | | NULL | | | updated_at | datetime | YES | | NULL | | | is_hidden | int(11) | YES | | 0 | | +--------------+--------------+------+-----+---------+-------+
奇怪的是,较旧的记录似乎有 auto_incremented。所以我的一半记录有预期的 ID,一半没有
我想做的是将此列设置为 auto_increment,然后运行执行以下操作的语句:
- 采用 created_at ASC 排序的所有 feed_items 其中 id 为 0
- 对于这些项目中的每一个,我想将 id 设置为前一个项目的 id + 1
虽然我不太喜欢 SQL,但我不想破坏我的实时服务器上的数据。
谁能给个建议?
最佳答案
根据您的表的大小,以及使其脱机的可能性,您可以简单地创建一个具有相同字段模式的第二个表并插入选择您的数据......
INSERT INTO _YourSecondTableName_ (feed_id,title,description,item_link,item_updated,item_id,created_at,updated_at,is_hidden)
SELECT feed_id,title,description,item_link,item_updated,item_id,created_at,updated_at,is_hidden
FROM _YourFirstTableName_
ORDER BY created_at ASC
然后您可以删除原始表并重命名新表 ...
关于mysql - 如何在不丢失数据的情况下自动递增此表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6321571/