如何对 MySQL 中的行进行唯一编号?

How to uniquely number rows in MySQL?

我在 table 中使用复合主键,例如

CREATE TABLE t
ADD firstId INT,
ADD secondId INT,
ADD PRIMARY KEY (firstId, secondId)
ADD KEY...,
ADD FOREIGN KEY...,
...

并想改为使用代理主键。为此,我需要为现有行生成唯一值。我不想使用自动增量,因为未来的 ids 是使用 hibernate_sequence 生成的。只有 10k 行,所以速度无关紧要,但我很好奇,是否有比加载所有行并逐行更新更简单的方法(这很乏味,因为我不能使用休眠,因为它必须完成在创建会话工厂之前)。

我不能使用像 firstId + N * secondId 这样的任何公式,因为它不适合 INT 范围(而且我不想使用更长的 ID)。

类似

UPDATE t SET id = row_number + 1

会很完美,但是 MySQL 中没有 row_number

那么我怎样才能对 MySQL 中的行进行唯一编号?

您可以通过某种方式模拟它 - 您可能想尝试 this

您可以创建一个 AUTO_INCREMENT PRIMARY KEY,然后删除 AUTO_INCREMENT 选项。

假设以下架构和数据:

create table t (
  firstId int not null,
  secondId int not null,
  primary key (firstId, secondId),
  index (secondId, firstId)
);

insert into t(firstId, secondId) values (1, 1);
insert into t(firstId, secondId) values (1, 2);
insert into t(firstId, secondId) values (2, 1);
insert into t(firstId, secondId) values (2, 2);

执行以下查询:

set foreign_key_checks = 0;

alter table t drop primary key;
alter table t add unique key (firstId, secondId);
alter table t add column id int auto_increment primary key first;
alter table t modify id int not null;

set foreign_key_checks = 1;

现在 table 将包含:

| id  | firstId | secondId |
| --- | ------- | -------- |
| 1   | 1       | 1        |
| 2   | 1       | 2        |
| 3   | 2       | 1        |
| 4   | 2       | 2        |

并且 table 架构将是:

CREATE TABLE `t` (
  `id` int(11) NOT NULL,
  `firstId` int(11) NOT NULL,
  `secondId` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `firstId` (`firstId`,`secondId`),
  KEY `secondId` (`secondId`,`firstId`)
)

db-fiddle

注意:如果当前PRIMARY KEY被外键使用,你只需要禁用foreign_key_checks