zoukankan      html  css  js  c++  java
  • A2-02-26.DML- MySQL LAST_INSERT_ID Function

    转载自:http://www.mysqltutorial.org/mysql-last_insert_id.aspx

    MySQL LAST_INSERT_ID Function

     

    Summary: in this tutorial, you will learn how to use the MySQL LAST_INSERT_ID function to obtain the generated sequence number of the last insert row.

    Introduction to MySQL LAST_INSERT_ID function

    In database design, you often use a surrogate key to generate unique integer values for the primary key column using the AUTO_INCREMENT attribute.

    It means when you insert a new row into the table that has an AUTO_INCREMENT column, MySQL automatically generates a unique integer and use it for the column.

    For more information on how to set the AUTO_INCREMENT attribute for a column, check it out the MySQL sequence tutorial.

    You can obtain the generated sequence number using the MySQL LAST_INSERT_ID function and use the number for the next statements e.g., inserting a new row into a correlated table.

    MySQL LAST_INSERT_ID example

    Let’s take a look at an example of using MySQL LAST_INSERT_ID  function.

    First, create a new table named tbl for testing. In the tbl table, you set the  AUTO_INCREMENT attribute for the id column.

    Second, insert a new row into the tbl table.

    Third, use the MySQL LAST_INSERT_ID function to get the last insert id that MySQL has been generated.

    mysql last_insert_id

    It’s important to note that if you insert multiple rows into a table using a single INSERT statement, the LAST_INSERT_ID function returns the last insert id of the first row.

    Suppose the AUTO_INCREMENT column has current value as 1 and you insert 3 rows into the table. When you use the LAST_INSERT_ID function to get the last insert id, you will get 2 instead of 4.

    The following statement inserts 3 rows into the  tbl table and gets the last insert id using the LAST_INSERT_ID function.

    mysql last_insert_id multiple inserts

    Check the data of the tbl table:

    mysql last_insert_id tbl table

    The LAST_INSERT_ID function works based on client-independent principle. It means the value returned by the LAST_INSERT_ID function for a specific client is the value generated by that client only. This ensures that each client can obtain its own unique ID.

    In this tutorial, we have shown you how to use the MySQL LAST_INSERT_ID function to get the sequence number of the last row that has been inserted into a table.

  • 相关阅读:
    Django_环境配置(一)
    python 使用sub替换时报错“re.error: bad escape P”或 “SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes”
    python 获取异常全部信息
    Flink入门 构建一个应用
    Flink入门 本地环境搭建
    mysql数据库 使用分析工具 进行慢查询分析
    Windows环境下搭建 【ElasticSearch】
    SpringBoot 事务的控制
    spring boot 数据库事务检查
    利用jenkins一键部署项目
  • 原文地址:https://www.cnblogs.com/zhuntidaoren/p/9519156.html
Copyright © 2011-2022 走看看