MySQL 中與 SQL Server 函式 SCOPE_IDENTITY() 等效的函式是什麼?


在 MySQL 中,與 SQL Server 函式 SCOPE_IDENTITY() 等效的函式是 LAST_INSERT_ID()。語法如下

SELECT LAST_INSERT_ID().

它返回最後插入記錄的 id。

此處,我將建立一個帶有主鍵列的表。以下是 last_insert_id() 的演示。

首先,讓我們建立兩個表。建立第一個表的查詢如下

<TestOnLastInsertIdDemo>

mysql> create table TestOnLastInsertIdDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(StudentId)
   -> );
Query OK, 0 rows affected (0.95 sec)

現在建立第二個表。查詢如下

<TestOnLastInsertIdDemo2>

mysql> create table TestOnLastInsertIdDemo2
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (2.79 sec)

使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into TestOnLastInsertIdDemo2 values(),(),(),(),(),(),(),();
Query OK, 8 rows affected (0.21 sec)
Records: 8 Duplicates: 0 Warnings: 0

現在在表‘TestOnLastInsertIdDemo2’上建立一個觸發器。建立表的查詢如下

mysql> delimiter //
mysql> create trigger insertingTrigger after insert on TestOnLastInsertIdDemo
   -> for each row begin
   -> insert into TestOnLastInsertIdDemo2 values();
   -> end;
   -> //
Query OK, 0 rows affected (0.19 sec)
mysql> delimiter ;

如果你將記錄插入到 TestOnLastInsertIdDemo 表中,則 last_insert_id() 返回 1。插入記錄的查詢如下

mysql> insert into TestOnLastInsertIdDemo values();
Query OK, 1 row affected (0.31 sec)

使用函式 last_insert_id()。查詢如下

mysql> select last_insert_id();

以下是輸出

+------------------+
| last_insert_id() |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

在上面的示例輸出中,它給出了 1,因為 last_insert_id() 只使用原始表,而不在觸發器表中。

更新於: 2019 年 7 月 30 日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告