Determining Identity of Newly Created Records in MySQL
When working with databases, it's often necessary to retrieve the unique identifier assigned to newly created records. In SQL Server, the SCOPE_IDENTITY() function serves this purpose. However, if you're using MySQL, its capabilities differ.
Equivalence in MySQL: LAST_INSERT_ID()
The MySQL equivalent of SCOPE_IDENTITY() is the LAST_INSERT_ID() function. It retrieves the ID of the last auto-increment value generated by the database.
Example Usage
CREATE TABLE Product ( ProductID INT AUTO_INCREMENT PRIMARY KEY ); INSERT INTO Product (Name) VALUES ('New Product'); # Get the ID of the newly created record SELECT LAST_INSERT_ID();
This query will return the ProductID of the newly inserted record.
Note on Triggered Insertions
It's important to note that LAST_INSERT_ID() returns the ID of the last auto-increment generated within the current session or transaction. In the case of insert triggers that perform additional inserts, LAST_INSERT_ID() will return the ID of the original table, not the table that was inserted into during the trigger.
Conclusion
Understanding the MySQL equivalent of SQL Server functions is crucial for working effectively with cross-platform database applications. By utilizing LAST_INSERT_ID(), you can retrieve the identity of newly created records within MySQL.
The above is the detailed content of How to Get the ID of Newly Created Records in MySQL?. For more information, please follow other related articles on the PHP Chinese website!