Problem with MySql INSERT MAX()+1(MySql INSERT MAX()+1 的问题)
问题描述
我有一个包含许多用户的表.在该表中,我有一个名为 user_id (INT) 的列,我想为每个人分别递增.user_id 必须从 1 开始
I have a single table containing many users. In that table I have column called user_id (INT), which I want increment separately for each person. user_id MUST start at 1
我准备了一个简单的例子:
I've prepared a simple example:
Showing all names
+--------------+-----------------------+
| user_id | name |
+--------------+-----------------------+
| 1 | Bob |
| 1 | Marry |
| 2 | Bob |
| 1 | John |
| 3 | Bob |
| 2 | Marry |
+--------------+-----------------------+
Showing only where name = Bob
+--------------+-----------------------+
| user_id | name |
+--------------+-----------------------+
| 1 | Bob |
| 2 | Bob |
| 3 | Bob |
+--------------+-----------------------+
以下查询将执行此操作,但仅当表中已存在Bob"时才有效...
The following query will do this, but it will only work if 'Bob' already exists in the table...
INSERT INTO users(user_id, name) SELECT(SELECT MAX(user_id)+1 from users where
name='Bob'), 'Bob';
如果 Bob 不存在(第一个条目),则 user_id 设置为 0(零).这就是问题.我需要 user_id 从 1 而不是 0 开始.
If Bob does not exist (first entry) user_id is set to 0 (zero). This is the problem. I need the user_id to start from 1 not 0.
推荐答案
你可以这样使用:
INSERT INTO users (user_id, name)
SELECT 1 + coalesce((SELECT max(user_id) FROM users WHERE name='Bob'), 0), 'Bob';
但是这样的查询可能会导致竞争条件.确保您处于事务中并在运行用户表之前锁定它.否则你可能会得到两个号码相同的 Bob.
But such query can lead to a race condition. Make sure you are in a transaction and you lock the users table before running it. Otherwise you might end up with two Bobs with the same number.
这篇关于MySql INSERT MAX()+1 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySql INSERT MAX()+1 的问题
基础教程推荐
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
