V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
zjx14250
V2EX  ›  MySQL

求问 Mysql 中 last_insert_id()语句的使用?

  •  
  •   zjx14250 · 2016-11-08 16:55:06 +08:00 · 2941 次点击
    这是一个创建于 2732 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一开始建个数据库 MariaDB [test]> create table auto( -> i smallint not null auto_increment, -> name varchar(10), -> primary key(i) -> ) -> ; Query OK, 0 rows affected (0.02 sec)

    然后执行一条插入语句 MariaDB [test]> insert into auto values(1,'1'),(0,'2'),(null,'3'); Query OK, 3 rows affected (0.00 sec) 此时执行 last_insert_id ()结果为 1 再执行一条语句 MariaDB [test]> insert into auto values(4,'4'); Query OK, 1 row affected (0.00 sec) 此时执行 last_insert_id ()结果为 2 再执行一条语句 MariaDB [test]> insert into auto values(5,'104'); 此时执行 last_insert_id ()结果还是为 2

    求问为什么没有变??

    7 条回复    2016-11-09 14:13:53 +08:00
    MajorAdam
        1
    MajorAdam  
       2016-11-08 17:09:30 +08:00 via Android
    第二次应该返回 4 吧
    MajorAdam
        2
    MajorAdam  
       2016-11-08 17:11:07 +08:00 via Android   ❤️ 1
    只有自增字段由 mysql 来分配时, last_insert_id()才可能得到正确的值
    MajorAdam
        3
    MajorAdam  
       2016-11-08 17:11:24 +08:00 via Android
    problem solved
    fupenghao
        4
    fupenghao  
       2016-11-09 11:19:25 +08:00
    并没解决。。。。第二次返回的是 2
    fupenghao
        5
    fupenghao  
       2016-11-09 11:19:32 +08:00
    MajorAdam
        6
    MajorAdam  
       2016-11-09 14:08:52 +08:00   ❤️ 1
    @fupenghao 你的自增 id 是自己赋值的 4,不是 mysql 自动生成的 4,只有自增字段由 mysql 来分配时,last_insert_id()才可能得到正确的值
    MajorAdam
        7
    MajorAdam  
       2016-11-09 14:13:53 +08:00
    "然后执行一条插入语句 MariaDB [test]> insert into auto values(1,'1'),(0,'2'),(null,'3'); Query OK, 3 rows affected (0.00 sec) 此时执行 last_insert_id ()结果为 1" 这是不可能的,此时应为 2
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2443 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:17 · PVG 22:17 · LAX 07:17 · JFK 10:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.