Lucia
Lucia

Reputation: 4767

Reset auto increment column value in script mysql

I have two mysql tables, one needs to start its auto-increment column id with the last value of the last inserted row in the other table (plus 1).

According to mysql manual you can restart the value of an auto increment column like this:

mysql> ALTER TABLE tbl AUTO_INCREMENT = 100;

However, this is not possible:

mysql> ALTER TABLE tb2 AUTO_INCREMENT = (SELECT MAX(id) FROM tbl1);

I need to perform something like this because I'm filling the tables using a script. Is there another way to achieve it?

Upvotes: 2

Views: 3006

Answers (3)

laffuste
laffuste

Reputation: 17105

What about create a dummy record and increment?

-- insert dummy forcing id
INSERT INTO 'tb2' (ID, NAME, ...)
VALUES (SELECT MAX(id) FROM tb1, "dummy", ...);

-- automagically increment to last id + 1
ALTER TABLE `tb2' AUTO_INCREMENT = 1; -- only myISAM

-- delete dummy
DELETE FROM 'tb2' WHERE NAME="dummy";

Upvotes: 0

1myb
1myb

Reputation: 3596

IT IS USING THIS SCRIPT

ALTER TABLE `people` AUTO_INCREMENT =1

where people is my table, or you can do this through GUI (operation tab of phpmyadmin with current table selected)

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839114

I think you are trying to use the auto-increment column for something it is not well suited to. If you care about the exact values that get inserted then it shouldn't be auto-increment.

Upvotes: 2

Related Questions