2014-07-16

MySQL 更新并返回计数

Views: 13301 | 6 Comments

对于想使用 MySQL 实现简单 ID 分配器, 一般就是设置一个整数字段, 然后想分配的时候加 1 并返回. 新手往往犯错误, 先执行一条 update 语句, 然后再 select 那个字段. 但这是错误的!

正确的方式应该是使用 last_insert_id() 函数:

update mytable set counter=last_insert_id(counter+1);
select last_insert_id();

Related posts:

  1. MySQL 建立外键约束
  2. 史上最强大的PHP MySQL操作类
  3. MySQL 基本配置
  4. MySQL”海量数据”查询性能分析
  5. MySQL 数据库双主配置
Posted by ideawu at 2014-07-16 13:51:59

6 Responses to "MySQL 更新并返回计数"

Leave a Comment