如何讓 MySQL 表的主鍵自動增加?


要讓 MySQL 表的主鍵自動增加,請使用以下語法

CREATE TABLE yourTableName
   (
   yourColumnName INT(6) ZEROFILL NOT NULL AUTO_INCREMENT,
   PRIMARY KEY(yourColumnName)
   );

讓我們先建立一個表,並設定主鍵自動增加 −

mysql> CREATE TABLE DemoTable
   (
   UserId INT(6) ZEROFILL NOT NULL AUTO_INCREMENT,
   PRIMARY KEY(UserId)
   );
Query OK, 0 rows affected (0.81 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> INSERT INTO DemoTable values();
Query OK, 1 row affected (0.12 sec)

mysql> INSERT INTO DemoTable values();
Query OK, 1 row affected (0.13 sec)

mysql> INSERT INTO DemoTable values();
Query OK, 1 row affected (0.10 sec)

mysql> INSERT INTO DemoTable values();
Query OK, 1 row affected (0.44 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

將生成以下輸出 −

+--------+
| UserId |
+--------+
| 000001 |
| 000002 |
| 000003 |
| 000004 |
+--------+
4 rows in set (0.00 sec)

更新日期:2019 年 7 月 30 日

1000+ 瀏覽量

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.