【问题标题】:How to add auto_increment field to a table with huge data?如何将 auto_increment 字段添加到包含大量数据的表中?
【发布时间】:2020-03-09 08:51:40
【问题描述】:

假设有一个表table_test,表中有大约1000万行数据。我想添加一个像key 这样的auto_increment 字段来做一些分页工作。让它发挥作用的最佳方法是什么?

表格结构如下:

# table_test

+---------------------------------------+--------------+------+-----+---------+-------+
| Field                                 | Type         | Null | Key | Default | Extra |
+---------------------------------------+--------------+------+-----+---------+-------+
| ad_id                                 | int(64)      | NO   | PRI | NULL    |       |
| account_id                            | varchar(64)  | YES  | MUL | NULL    |       |
| country                               | varchar(64)  | NO   | PRI | NULL    |       |
| image_hash                            | varchar(64)  | YES  |     | NULL    |       |
+---------------------------------------+--------------+------+-----+---------+-------+



| table_test | CREATE TABLE `table_test` (
  `ad_id` int(11) NOT NULL,
  `account_id` varchar(64) DEFAULT NULL,
  `country` varchar(64) NOT NULL,
  `image_hash` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`,`country`),
  KEY `account_id` (`account_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |

更新:

id 更改为ad_idad_id 与字段country 一起是唯一键,因此ad_id 本身可能重复。

【问题讨论】:

  • Id 有重复项?
  • @Nae 是的,这里的意思是ad_id,和country 一起是独一无二的。我已经更新了我上面的问题
  • 根本没有回答所提出的问题,而是根据看到的最后一行进行分页。嗯,下一页是 last_seen=something & rows = 10 你可以保留这个结构。缺点是复制看起来不会对这种结构有效
  • @exussum 感谢您的回复,但我不完全理解您的建议。你能帮我说清楚吗?

标签: mysql


【解决方案1】:

我会去:

-- drop PK as AUTO increment demands being the PK
ALTER TABLE table_test DROP PRIMARY KEY;
-- add Id as PK and the first column
ALTER TABLE table_test ADD Id INT AUTO_INCREMENT PRIMARY KEY FIRST;
-- make sure the old PK is unique
ALTER TABLE table_test ADD CONSTRAINT table_test_uk UNIQUE (ad_id, country);

或许:

CREATE TABLE table_test2 LIKE table_test;
ALTER TABLE table_test2 DROP PRIMARY KEY;
-- add Id as PK and the first column
ALTER TABLE table_test2 ADD Id INT AUTO_INCREMENT PRIMARY KEY FIRST;
-- make sure the old PK is unique
ALTER TABLE table_test2 ADD CONSTRAINT table_test2_uk UNIQUE (ad_id, country);
INSERT INTO table_test2(ad_id, account_id, country, image_hash)
SELECT ad_id, account_id, country, image_hash FROM table_test;
DROP TABLE table_test;
RENAME TABLE table_test2 TO table_test;

【讨论】:

  • 感谢回复,操作好像很费时间,请问如何加快速度?
  • @jiaJimmy 添加了另一种方法。
【解决方案2】:

改变你的桌子

ALTER TABLE table_test CHANGE id id INT(11) NOT NULL AUTO_INCREMENT;

【讨论】:

    【解决方案3】:

    您已经可以将“id”列用作自动增量(除非您使用 UUID 或其他策略)。

    您可以查看以下关于如何更改表格以向表格添加自动增量的答案: ALTER table - adding AUTOINCREMENT in MySQL

    编辑: 如果您希望添加一个将自动递增的新列,您可以使用以下命令: ALTER TABLE table_test ADD id INT AUTO_INCREMENT;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 2015-10-10
      相关资源
      最近更新 更多