mysql before insert,MySql INSERT MAX()+ 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 |

+--------------+-----------------------+

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';

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.

解决方案

You can use something like this:

INSERT INTO users (user_id, name)

SELECT 1 + coalesce((SELECT max(user_id) FROM users WHERE name='Bob'), 0), '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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值