0

我有一个 MySQL 数据库,其中包含一个带有 auto_increment 主键的表。

考虑以下定义对于此示例已足够:

create table test(id integer not null auto_increment primary key) engine=innodb;

现在,通常我会使用以下语法插入此表:

insert into test() values();

这将适当地更新 auto_increment 值,这很好。

但是,我想在此表中插入一个高值(例如 1000000),但让它更新 auto_increment ID。

是否可以以不影响 auto_increment ID 值的方式将高值插入此表?

我知道这是一种糟糕的做法,但它会大大简化我必须做的一些事情。

提前致谢。

4

7 回答 7

5

MySQL 5.0 允许您将任意值插入到自动递增字段中,但这确实会改变用于自动递增的下一个值。尽管您可以更改自动增量字段将使用的“下一个数字”(使用ALTER TABLE t AUTO_INCREMENT = number),但这必须大于该列中当前的最大值。

所以,不,您似乎无法实现您的要求。

于 2009-10-05T21:58:25.057 回答
2

你可以给你的行你喜欢的 id。例如,给定以下表定义:

CREATE TABLE IF NOT EXISTS `stack-test` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255),
  PRIMARY KEY  (`id`)
);

以下查询将插入具有自动生成 id 的行:

INSERT INTO `stack-test` (name) VALUES ('Peter');

此查询将插入具有用户定义 ID 的行:

INSERT INTO `stack-test` (id, name) VALUES (5, 'Joe');

通过查询所有行进行验证:

SELECT * FROM `stack-test`;

输出:

+----+-------+
| id | name  |
+----+-------+
|  1 | peter |
|  5 | Joe   |
+----+-------+

更新:请阅读,您不想影响AUTO_INCREMENT价值。正如 staticsan 所提到的,该AUTO_INCREMENT字段自动使用最大值加一。有一条语句将计数器重置为某个值,但这仅在表中没有更高值时才有效:

ALTER TABLE `stack-test` AUTO_INCREMENT = 2;
于 2009-10-05T21:58:53.307 回答
1

我有一个类似的问题,虽然我喜欢上面的答案,但我通过使用两个表来解决它。一个用于高ID,另一个用于低ID。它非常适合我的特殊情况。

于 2012-11-12T15:17:58.657 回答
0

sorry for stating the bleedin' obvious, and I'm not an RDBMS specialist at all, but isn't your requirement so "unorthodox" that it dictates another approach? You yourself say you know this is "terrible practice". Isn't the thing about auto-increment fields that they serve one purpose and one purpose only: to assign a unique ID to a particular record, and isn't it, um, absolutely wrong to attribute any significance whatever to the actual value?

So, ever so tentatively, might I suggest using another field to do what you want?

于 2014-07-24T18:36:59.830 回答
0

保留一些初始值而不是最终值怎么样?我的意思是,保留 id,比如保留少于 1000 个。将自动增量种子设为 1001,以便新插入在此之后具有值,并使用 IDENTITY INSERT 在保留范围内添加值。

希望能帮助到你。

于 2012-08-27T11:21:18.847 回答
0

我不这么认为——自动递增的字段必须是主键,因此不能为空。

于 2009-10-05T21:49:08.490 回答
0

这是不可能的。当计数器最终达到您插入的那个非常高的数字时,要让事情按照您建议的方式运行,会引入一个重复的 auto_increment 值。

于 2009-10-05T21:58:43.743 回答