我在表中使用复合主键,例如
CREATE TABLE t
ADD firstId INT,
ADD secondId INT,
ADD PRIMARY KEY (firstId, secondId)
ADD KEY...,
ADD FOREIGN KEY...,
...
并且希望改用代理主键。为此,我需要为现有行生成唯一值。我不想使用自动增量,因为将来的 id 是使用 hibernate_sequence 生成的。只有 10k 行,所以速度几乎不重要,但我很好奇,是否有比加载所有行并逐一更新它们更简单的东西(这非常乏味,因为我不能使用休眠,因为它必须完成在创建 session 工厂之前)。
我无法使用任何公式,如 firstId + N * secondaryId
,因为它不适合 INT 范围(而且我不想使用更长的 ID)。
类似的东西
UPDATE t SET id = row_number + 1
就完美了,但是 MySQL 中没有 row_number
。
那么如何在 MySQL 中对行进行唯一编号呢?
最佳答案
您可以创建一个 AUTO_INCRMENT PRIMARY KEY
,然后删除 AUTO_INCRMENT
选项。
假设以下架构和数据:
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;
现在表格将包含:
| id | firstId | secondId |
| --- | ------- | -------- |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 2 |
表架构将是:
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`)
)
注意:如果当前 PRIMARY KEY 被外键使用,则只需禁用 foreign_key_checks
即可。
关于mysql - 如何在MySQL中对行进行唯一编号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57762007/