MySQL - 重置自動遞增



大多數 MySQL 表使用順序值來表示記錄,例如序列號。MySQL 使用“AUTO_INCREMENT”來自動處理此問題,而不是逐個手動插入每個值。

MySQL 中的 AUTO_INCREMENT

MySQL 中的 AUTO_INCREMENT 用於在向表中新增新記錄時自動生成按升序排列的唯一數字。對於需要每一行都有唯一值的應用程式,它非常有用。

當您將列定義為 AUTO_INCREMENT 列時,MySQL 會處理其餘部分。它從值 1 開始,併為每條新記錄遞增 1,為您的表建立一系列唯一數字。

示例

以下示例演示了在資料庫表中的列上使用 AUTO_INCREMENT。在這裡,我們正在建立一個名為“insect”的表,並將 AUTO_INCREMENT 應用於“id”列。

CREATE TABLE insect (
   id INT UNSIGNED NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (id),
   name VARCHAR(30) NOT NULL,
   date DATE NOT NULL,
   origin VARCHAR(30) NOT NULL
);

現在,您無需在插入記錄時手動指定“id”列的值。相反,MySQL 會為您處理它,從 1 開始,每條新記錄遞增 1,為您的表建立一系列唯一數字。要插入表中其他列的值,請使用以下查詢:

INSERT INTO insect (name,date,origin) VALUES
('housefly','2001-09-10','kitchen'),
('millipede','2001-09-10','driveway'),
('grasshopper','2001-09-10','front yard');

顯示的 insect 表如下所示。在這裡,我們可以看到“id”列的值是由 MySQL 自動生成的:

id 名稱 日期 來源
1 家蠅 2001-09-10 廚房
2 千足蟲 2001-09-10 車道
3 蚱蜢 2001-09-10 前院

MySQL 重置自動遞增

表上的預設 AUTO_INCREMENT 值從 1 開始,即插入的值通常從 1 開始。但是,MySQL 還提供將這些 AUTO_INCREMENT 值重置為另一個數字的規定,使序列能夠從指定重置值開始插入。

您可以透過三種方式重置 AUTO_INCREMENT 值:使用 ALTER TABLE、TRUNCATE TABLE 或刪除並重新建立表。

使用 ALTER TABLE 語句重置

MySQL 中的 ALTER TABLE 語句用於更新表或對其進行任何更改。因此,使用此語句重置 AUTO_INCREMENT 值是一個完全有效的選擇。

語法

以下是使用 ALTER TABLE 重置自動遞增的語法:

ALTER TABLE table_name AUTO_INCREMENT = new_value;

示例

在這個示例中,我們使用 ALTER TABLE 語句將 AUTO_INCREMENT 值重置為 5。請注意,新的 AUTO_INCREMENT 值必須大於表中已存在的記錄數:

ALTER TABLE insect AUTO_INCREMENT = 5;

獲得的輸出如下:

Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

現在,讓我們將另一個值插入上面建立的“insect”表中,並使用以下查詢檢查新的結果集:

INSERT INTO insect (name,date,origin) VALUES 
('spider', '2000-12-12', 'bathroom'),
('larva', '2012-01-10', 'garden');

我們得到的結果如下所示:

Query OK, 2 row affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

要驗證您插入的新記錄是否將從設定為 5 的 AUTO_INCREMENT 值開始,請使用以下 SELECT 查詢:

SELECT * FROM insect;

獲得的表如下所示:

id 名稱 日期 來源
1 家蠅 2001-09-10 廚房
2 千足蟲 2001-09-10 車道
3 蚱蜢 2001-09-10 前院
5 蜘蛛 2000-12-12 浴室
6 幼蟲 2012-01-10 花園

使用 TRUNCATE TABLE 語句重置

另一種將自動遞增列重置為預設值的方法是使用 TRUNCATE TABLE 命令。這將刪除表的現有資料,當您插入新記錄時,AUTO_INCREMENT 列將從頭開始(通常為 1)。

示例

以下是如何將 AUTO_INCREMENT 值重置為預設值“0”的示例。為此,首先使用 TRUNCATE TABLE 命令清空上面建立的“insect”表,如下所示:

TRUNCATE TABLE insect;

獲得的輸出如下:

Query OK, 0 rows affected (0.04 sec)

要驗證表中的記錄是否已刪除,請使用以下 SELECT 查詢:

SELECT * FROM insect;

產生的結果如下:

Empty set (0.00 sec)

現在,使用以下 INSERT 語句再次插入值。

INSERT INTO insect (name,date,origin) VALUES
('housefly','2001-09-10','kitchen'),
('millipede','2001-09-10','driveway'),
('grasshopper','2001-09-10','front yard'),
('spider', '2000-12-12', 'bathroom');

執行上述程式碼後,我們得到以下輸出:

Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

您可以使用以下 SELECT 查詢驗證表中的記錄是否已重置:

SELECT * FROM insect;

顯示的表如下所示:

id 名稱 日期 來源
1 家蠅 2001-09-10 廚房
2 千足蟲 2001-09-10 車道
3 蚱蜢 2001-09-10 前院
4 蜘蛛 2000-12-12 浴室

使用客戶端程式重置自動遞增

我們還可以使用客戶端程式重置自動遞增。

語法

要透過 PHP 程式重置自動遞增,我們需要使用mysqli函式query()執行“ALTER TABLE”語句,如下所示:

$sql = "ALTER TABLE INSECT AUTO_INCREMENT = 5";
$mysqli->query($sql);

要透過 JavaScript 程式重置自動遞增,我們需要使用mysql2庫的query()函式執行“ALTER TABLE”語句,如下所示:

sql = "ALTER TABLE insect AUTO_INCREMENT = 5";
con.query(sql)

要透過 Java 程式重置自動遞增,我們需要使用JDBC函式execute()執行“ALTER TABLE”語句,如下所示:

String sql = "ALTER TABLE insect AUTO_INCREMENT = 5";
statement.execute(sql);

要透過 Python 程式重置自動遞增,我們需要使用MySQL Connector/Pythonexecute()函式執行“ALTER TABLE”語句,如下所示:

reset_auto_inc_query = "ALTER TABLE insect AUTO_INCREMENT = 5"
cursorObj.execute(reset_auto_inc_query)

示例

以下是程式:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$db = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);
if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error); exit(); } //printf('Connected successfully.
'); //lets create a table $sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)"; if($mysqli->query($sql)){ printf("Insect table created successfully....!\n"); } //now lets insert some records $sql = "INSERT INTO insect (name,date,origin) VALUES ('housefly','2001-09-10','kitchen'), ('millipede','2001-09-10','driveway'), ('grasshopper','2001-09-10','front yard')"; if($mysqli->query($sql)){ printf("Records inserted successfully....!\n"); } //display table records $sql = "SELECT * FROM INSECT"; if($result = $mysqli->query($sql)){ printf("Table records: \n"); while($row = mysqli_fetch_array($result)){ printf("Id: %d, Name: %s, Date: %s, Origin: %s", $row['id'], $row['name'], $row['date'], $row['origin']); printf("\n"); } } //lets reset the autoincrement using alter table statement... $sql = "ALTER TABLE INSECT AUTO_INCREMENT = 5"; if($mysqli->query($sql)){ printf("Auto_increment reset successfully...!\n"); } //now lets insert some more records.. $sql = "INSERT INTO insect (name,date,origin) VALUES ('spider', '2000-12-12', 'bathroom'), ('larva', '2012-01-10', 'garden')"; $mysqli->query($sql); $sql = "SELECT * FROM INSECT"; if($result = $mysqli->query($sql)){ printf("Table records(after resetting autoincrement): \n"); while($row = mysqli_fetch_array($result)){ printf("Id: %d, Name: %s, Date: %s, Origin: %s", $row['id'], $row['name'], $row['date'], $row['origin']); printf("\n"); } } if($mysqli->error){ printf("Error message: ", $mysqli->error); } $mysqli->close();

輸出

獲得的輸出如下所示:

Insect table created successfully....!
Records inserted successfully....!
Table records: 
Id: 1, Name: housefly, Date: 2001-09-10, Origin: kitchen
Id: 2, Name: millipede, Date: 2001-09-10, Origin: driveway
Id: 3, Name: grasshopper, Date: 2001-09-10, Origin: front yard
Auto_increment reset successfully...!
Table records(after resetting autoincrement):
Id: 1, Name: housefly, Date: 2001-09-10, Origin: kitchen
Id: 2, Name: millipede, Date: 2001-09-10, Origin: driveway
Id: 3, Name: grasshopper, Date: 2001-09-10, Origin: front yard
Id: 5, Name: spider, Date: 2000-12-12, Origin: bathroom
Id: 6, Name: larva, Date: 2012-01-10, Origin: garden    

var mysql = require('mysql2');
var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "Nr5a0204@123"
});

// Connecting to MySQL
con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");
    console.log("--------------------------");

    // Create a new database
    sql = "Create Database TUTORIALS";
    con.query(sql);

    sql = "USE TUTORIALS";
    con.query(sql);

    sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL);"
    con.query(sql);

    sql = "INSERT INTO insect (name,date,origin) VALUES ('housefly','2001-09-10','kitchen'),('millipede','2001-09-10','driveway'),('grasshopper','2001-09-10','front yard');"
    con.query(sql);

    sql = "SELECT * FROM insect;"
    con.query(sql, function(err, result){
      if (err) throw err
      console.log("**Records of INSECT Table:**");
      console.log(result);
      console.log("--------------------------");
    });

    sql = "ALTER TABLE insect AUTO_INCREMENT = 5";
    con.query(sql);

    sql = "INSERT INTO insect (name,date,origin) VALUES ('spider', '2000-12-12', 'bathroom'), ('larva', '2012-01-10', 'garden');"
    con.query(sql);

    sql = "SELECT * FROM insect;"
    con.query(sql, function(err, result){
      console.log("**Records after modifying the AUTO_INCREMENT to 5:**");
      if (err) throw err
      console.log(result);
    });
});    

輸出

獲得的輸出如下所示:

 
Connected!
--------------------------
**Records of INSECT Table:**
[
  {id: 1,name: 'housefly',date: 2001-09-09T18:30:00.000Z,origin: 'kitchen'},
  {id: 2,name: 'millipede',date: 2001-09-09T18:30:00.000Z,origin: 'driveway'},
  {id: 3,name: 'grasshopper',date: 2001-09-09T18:30:00.000Z,origin: 'front yard'}
]
--------------------------
**Records after modifying the AUTO_INCREMENT to 5:**
[
  {id: 1,name: 'housefly',date: 2001-09-09T18:30:00.000Z,origin: 'kitchen'},
  {id: 2,name: 'millipede',date: 2001-09-09T18:30:00.000Z,origin: 'driveway'},
  {id: 3,name: 'grasshopper',date: 2001-09-09T18:30:00.000Z,origin: 'front yard'},
  {id: 5,name: 'spider',date: 2000-12-11T18:30:00.000Z,origin: 'bathroom'},
  {id: 6,name: 'larva',date: 2012-01-09T18:30:00.000Z,origin: 'garden'}
]    
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ResetAutoIncrement {
    public static void main(String[] args) {
        String url = "jdbc:mysql://:3306/TUTORIALS";
        String user = "root";
        String password = "password";
        ResultSet rs;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, password);
            Statement st = con.createStatement();
            //System.out.println("Database connected successfully...!");
            String sql = "CREATE TABLE insect (id INT UNSIGNED NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL)";
            st.execute(sql);
            System.out.println("Table insect created successfully....!");
            //lets insert some records into it
            String sql1 = "INSERT INTO insect (name,date,origin) VALUES ('housefly','2001-09-10','kitchen'), ('millipede','2001-09-10','driveway'), ('grasshopper','2001-09-10','front yard')";
            st.execute(sql1);
            System.out.println("Records inserted successfully...!");
            //let print table records
            String sql2 = "SELECT * FROM insect";
            rs = st.executeQuery(sql2);
            System.out.println("Table records(before resetting auto-increment): ");
            while(rs.next()) {
                String name = rs.getString("name");
                String date = rs.getString("date");
                String origin = rs.getString("origin");
                System.out.println("Name: " + name + ", Date: " + date + ", Origin: " + origin);
            }
            //lets reset auto increment using ALTER table statement...
            String reset = "ALTER TABLE INSECT AUTO_INCREMENT = 5";
            st.execute(reset);
            System.out.println("Auto-increment reset successsfully...!");
            //lets insert some more records..
            String sql3 = "INSERT INTO insect (name,date,origin) VALUES ('spider', '2000-12-12', 'bathroom'), ('larva', '2012-01-10', 'garden')";
            st.execute(sql3);
            System.out.println("Records inserted successfully..!");
            String sql4 = "SELECT * FROM insect";
            rs = st.executeQuery(sql4);
            System.out.println("Table records(after resetting auto-increment): ");
            while(rs.next()) {
                String name = rs.getString("name");
                String date = rs.getString("date");
                String origin = rs.getString("origin");
                System.out.println("Name: " + name + ", Date: " + date + ", Origin: " + origin);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}    

輸出

獲得的輸出如下所示:

Table insect created successfully....!
Records inserted successfully...!
Table records(before resetting auto-increment): 
Name: housefly, Date: 2001-09-10, Origin: kitchen
Name: millipede, Date: 2001-09-10, Origin: driveway
Name: grasshopper, Date: 2001-09-10, Origin: front yard
Auto-increment reset successsfully...!
Records inserted successfully..!
Table records(after resetting auto-increment): 
Name: housefly, Date: 2001-09-10, Origin: kitchen
Name: millipede, Date: 2001-09-10, Origin: driveway
Name: grasshopper, Date: 2001-09-10, Origin: front yard
Name: spider, Date: 2000-12-12, Origin: bathroom
Name: larva, Date: 2012-01-10, Origin: garden     
import mysql.connector
# Establishing the connection 
connection = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='tut'
)
# Creating a cursor object 
cursorObj = connection.cursor()
# Creating the 'insect' table
create_table_query = '''
CREATE TABLE insect (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id),
    name VARCHAR(30) NOT NULL,
    date DATE NOT NULL,
    origin VARCHAR(30) NOT NULL
);
'''
cursorObj.execute(create_table_query)
print("Table 'insect' is created successfully!")
# Inserting records into the 'insect' table
insert_query = "INSERT INTO insect (Name, Date, Origin) VALUES (%s, %s, %s);"
values = [
    ('housefly', '2001-09-10', 'kitchen'),
    ('millipede', '2001-09-10', 'driveway'),
    ('grasshopper', '2001-09-10', 'front yard')
]
cursorObj.executemany(insert_query, values)
print("Values inserted successfully!")
# Displaying the contents of the 'insect' table
display_table_query = "SELECT * FROM insect;"
cursorObj.execute(display_table_query)
results = cursorObj.fetchall()
print("\ninsect Table:")
for result in results:
    print(result)
# Resetting the auto-increment value of the 'id' column
reset_auto_inc_query = "ALTER TABLE insect AUTO_INCREMENT = 5;"
cursorObj.execute(reset_auto_inc_query)
print("Auto-increment value reset successfully!")
# Inserting additional records into the 'insect' table
insert_query = "INSERT INTO insect (name, date, origin) VALUES ('spider', '2000-12-12', 'bathroom');"
cursorObj.execute(insert_query)
print("Value inserted successfully!")
insert_again_query = "INSERT INTO insect (name, date, origin) VALUES ('larva', '2012-01-10', 'garden');"
cursorObj.execute(insert_again_query)
print("Value inserted successfully!")
# Displaying the updated contents of the 'insect' table
display_table_query = "SELECT * FROM insect;"
cursorObj.execute(display_table_query)
results = cursorObj.fetchall()
print("\ninsect Table:")
for result in results:
    print(result)
# Closing the cursor and connection
cursorObj.close()
connection.close()    

輸出

獲得的輸出如下所示:

Table 'insect' is created successfully!
Values inserted successfully!

insect Table:
(1, 'housefly', datetime.date(2001, 9, 10), 'kitchen')
(2, 'millipede', datetime.date(2001, 9, 10), 'driveway')
(3, 'grasshopper', datetime.date(2001, 9, 10), 'front yard')
Auto-increment value reset successfully!
Value inserted successfully!
Value inserted successfully!

insect Table:
(1, 'housefly', datetime.date(2001, 9, 10), 'kitchen')
(2, 'millipede', datetime.date(2001, 9, 10), 'driveway')
(3, 'grasshopper', datetime.date(2001, 9, 10), 'front yard')
(5, 'spider', datetime.date(2000, 12, 12), 'bathroom')
(6, 'larva', datetime.date(2012, 1, 10), 'garden')
廣告