Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Thiết lập AUTO_INCREMENT khi tạo bảng trong MySQL

Bạn có thể đặt giá trị khởi đầu cho cột AUTO_INCREMENT ngay trong câu lệnh CREATE TABLE bằng từ khóa AUTO_INCREMENT = gia_tri ở cuối định nghĩa bảng.

Ví dụ minh họa

Tạo bảng, bắt đầu ID từ 30:

mysql> CREATE TABLE DemoTable (
    StudentId INT NOT NULL AUTO_INCREMENT,
    StudentFirstName VARCHAR(100),
    StudentLastName VARCHAR(100),
    StudentAge INT,
    StudentCountryName VARCHAR(100),
    PRIMARY KEY(StudentId)
) AUTO_INCREMENT = 30;

Chèn dữ liệu (không chỉ định StudentId):

mysql> INSERT INTO DemoTable(StudentFirstName, StudentLastName, StudentAge, StudentCountryName)
    -> VALUES('John', 'Smith', 21, 'US');
mysql> INSERT INTO DemoTable(StudentFirstName, StudentLastName, StudentAge, StudentCountryName)
    -> VALUES('Chris', 'Brown', 20, 'AUS');

Xem dữ liệu:

mysql> SELECT * FROM DemoTable;

Kết quả

+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentCountryName |
+-----------+------------------+-----------------+------------+--------------------+
| 30        | John             | Smith           | 21         | US                 |
| 31        | Chris            | Brown           | 20         | AUS                |
+-----------+------------------+-----------------+------------+--------------------+

Lưu ý: Giá trị AUTO_INCREMENT phải lớn hơn bất kỳ giá trị hiện có trong cột. Để thay đổi sau khi tạo bảng: ALTER TABLE DemoTable AUTO_INCREMENT = 100;.