Home > Database > Mysql Tutorial > How to Renumber Primary Key Indexes in MySQL for Sequential Values?

How to Renumber Primary Key Indexes in MySQL for Sequential Values?

DDD
Release: 2024-10-25 02:04:02
Original
1019 people have browsed it

How to Renumber Primary Key Indexes in MySQL for Sequential Values?

Renumbering Primary Key Indexes

A MySQL table can have a primary index (typically an 'id' column) whose values may not be numbered sequentially. To rectify this, consider the following approach:

Method:

Instead of manipulating temp tables, a more efficient technique is as follows:

SET @i=0;
UPDATE table_name SET column_name=(@i:=@i+1);
Copy after login

Explanation:

  1. Set a user-defined variable @i to 0.
  2. Run an UPDATE query on the table.
  3. For each row in the table, assign the value of @i to the column_name column.
  4. Increment @i by 1 after assigning the value.

Example:

Consider the following table:

id | name
----+--------
31  | John
35  | Mary
100 | David
Copy after login

The above method will update the table as follows:

id | name
----+--------
1   | John
2   | Mary
3   | David
Copy after login

The above is the detailed content of How to Renumber Primary Key Indexes in MySQL for Sequential Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template