MySQL 中等效於 SQL Server IDENTITY 列的內容是什麼?


MySQL 中等效於 Microsoft SQL Server IDENTITY 列的是 AUTO_INCREMENT。SQL Server 中的 IDENTITY 在 MySQL 中的作用與 AUTO_INCREMENT 相同。

語法如下 -

CREATE TABLE yourTableName
(
   yourColumnName1 dataType NOT NULL AUTO_INCREMENT,
   yourColumnName2 dataType,
   .
   .
   .
   N,
   PRIMARY KEY(yourColumnName1)
);

在 MySQL 中,如果你的列是自增的,你需要使用主鍵,否則 MySQL 將報錯。檢視錯誤 -

mysql> create table EquivalentOfIdentityInMySQL
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(30)
   -> );
ERROR 1075 (42000) − Incorrect table definition; there can be only one auto column and it
must be defined as a key

要消除上述錯誤,你需要將 ProductId 設為主鍵。將 ProductId 設為主鍵的 MySQL AUTO_INCREMENT 宣告如下 -

mysql> create table EquivalentOfIdentityInMySQL
   -> (
   -> ProductId int NOT NULL AUTO_INCREMENT,
   -> ProductName varchar(30)
   -> ,
   -> PRIMARY KEY(ProductId)
   -> );
Query OK, 0 rows affected (0.59 sec)

如果你沒有為 ProductId 列傳遞任何值,MySQL 會從 1 開始自動增量,並且下一個數字預設遞增 1。 

要檢查 ProductId 列,讓我們使用插入命令在表中插入一些記錄。查詢如下 -

mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-1');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-2');
Query OK, 1 row affected (0.14 sec)

mysql> insert into EquivalentOfIdentityInMySQL(ProductName) values('Product-34');
Query OK, 1 row affected (0.10 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 -

mysql> select *from EquivalentOfIdentityInMySQL;

輸出如下 -

+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
|         1 | Product-1   |
|         2 | Product-2   |
|         3 | Product-34  |
+-----------+-------------+
3 rows in set (0.00 sec)

檢視 ProductId 列,我們沒有為該列傳遞任何值,但我們得到的數字從 1 開始,下一個數字遞增 1。

更新於: 2019-7-30

8k+ 瀏覽量

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.