gpt4 book ai didi

mysql - 我想生成一个包含名字、姓氏和号码组合的自定义名称

转载 作者:行者123 更新时间:2023-11-29 09:51:15 25 4
gpt4 key购买 nike

现在,我们计划在每次用户注册(创建帐户)时自动生成 UID(唯一成员(member)编号/客户编号)的规则。

我们设定的规则:名字 姓氏 = FL+ 001(与这两个字母相关的数字,按帐户创建的时间顺序排列)即两个字母都是唯一的,只有当两个字母重复时,数字计数才会增加。

例如:

John Doe - JD001
John Denver - JD002
Jane Foster - JF001
Bob Bilkins - BB001
Bill Graham - BG001

最佳答案

假设您的users 表为:

create table users (
user_id int unsigned auto_increment primary key,
fname varchar(50) not null,
lname varchar(50) not null,
uid varchar(50) unique
);

创建另一个表,其中将保存所有用户首字母缩写的最后序列号:

create table uid_seq (
initials varchar(2) not null primary key,
seq int unsigned not null
);

然后为 users 表编写一个插入触发器,该触发器将增加给定首字母缩写的序列号并将其返回以生成 UID:

delimiter //
create trigger users_before_insert before insert on users
for each row begin
set @initials = concat(left(new.fname,1), left(new.lname, 1));
insert into uid_seq (initials, seq)
values (@initials, last_insert_id(1))
on duplicate key update seq = last_insert_id(seq + 1);
set new.uid = concat(@initials, lpad(last_insert_id(), 3, 0));
end //
delimiter ;

此方法是并发安全的,因为我们使用 INSERT .. ON DUPLICATE KEY UPDATE .. 并使用 LAST_INSERT_ID() 返回生成的值。这样两个用户将永远不会获得相同的 UID。在最坏的情况下,当服务器在处理插入时崩溃时,您可能会烧毁序列号。但是 - 如果您在事务中执行插入,那么这种情况也不会发生。

请注意,您仍然需要一个 AUTO_INCRMENT ID,因为这是找出您刚刚插入的行的唯一方法,除非您有一个自然的识别键。

关于mysql - 我想生成一个包含名字、姓氏和号码组合的自定义名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com