In MariaDB, LAST_INSERT_ID() è una funzione incorporata che restituisce il primo valore generato automaticamente inserito correttamente per un AUTO_INCREMENT colonna come risultato dell'ultimo INSERT eseguito dichiarazione.
Può anche essere chiamato con un argomento, nel qual caso restituisce il valore dell'espressione e la successiva chiamata a LAST_INSERT_ID() restituirà lo stesso valore.
Sintassi
La funzione può essere chiamata nei seguenti modi:
LAST_INSERT_ID()
LAST_INSERT_ID(expr)
Dove expr viene restituito e la chiamata successiva a LAST_INSERT_ID() restituirà lo stesso valore.
Esempio
Ad esempio, creiamo una tabella con un AUTO_INCREMENT colonna:
CREATE TABLE guest (
guest_id INT NOT NULL AUTO_INCREMENT,
guest_name VARCHAR(255) NOT NULL,
PRIMARY KEY (guest_id)
);
Il guest_id la colonna utilizza AUTO_INCREMENT per il suo valore.
Ora inserisci alcune righe:
INSERT INTO guest (guest_name) VALUES ('Homer');
INSERT INTO guest (guest_name) VALUES ('Bart');
INSERT INTO guest (guest_name) VALUES ('Marge');
Ora eseguiamo LAST_INSERT_ID() :
SELECT LAST_INSERT_ID(); Risultato:
+------------------+ | LAST_INSERT_ID() | +------------------+ | 3 | +------------------+
Restituisce 3 .
Ora, restituiamo tutte le righe della tabella per verificare che l'ultima riga abbia un AUTO_INCREMENT valore di 3 inserito:
SELECT *
FROM guest; Risultato:
+----------+------------+ | guest_id | guest_name | +----------+------------+ | 1 | Homer | | 2 | Bart | | 3 | Marge | +----------+------------+
Il guest_id la colonna va fino a 3 .
Incluso un argomento
Come accennato, se chiamata con un argomento, la funzione restituisce il valore dell'espressione e la successiva chiamata a LAST_INSERT_ID() restituirà lo stesso valore.
SELECT LAST_INSERT_ID(9); Risultato:
+-------------------+ | LAST_INSERT_ID(9) | +-------------------+ | 9 | +-------------------+
Ora chiamalo di nuovo, ma senza argomenti:
SELECT LAST_INSERT_ID(); Risultato:
+------------------+ | LAST_INSERT_ID() | +------------------+ | 9 | +------------------+
Restituisce comunque un valore di 9 .
Tuttavia, se continuiamo a inserire valori nel nostro guest tabella, il AUTO_INCREMENT continuerà da dove si era interrotto su quel tavolo:
INSERT INTO guest (guest_name) VALUES ('Lisa');
Ora eseguiamo LAST_INSERT_ID() :
SELECT LAST_INSERT_ID(); Risultato:
+------------------+ | LAST_INSERT_ID() | +------------------+ | 4 | +------------------+
Restituisce 4 .
Ed ecco come appare la tabella ora:
SELECT *
FROM guest; Risultato:
+----------+------------+ | guest_id | guest_name | +----------+------------+ | 1 | Homer | | 2 | Bart | | 3 | Marge | | 4 | Lisa | +----------+------------+
Per ulteriori informazioni su questa funzione, vedere la documentazione di MariaDB.