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 的问题


基础教程推荐
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01