我创建了一个表客户 但是当我插入第一个名字ex:anish时它可以自动生成的batchnumber当我给出名字'anish'时它将被取为前3个字符它应该在添加'001'之后选择'ani' 如果有一个多于1个相同的名称,给定其批号应该得到增量
这里我添加了一个示例输出
Firstname | Batchnumber
---------------------
Anish | Ani001
Uma | Uma001
Anish | Ani002
Uma | Uma002
Loki | Lok001
答案 0 :(得分:0)
SET @ndx = 0;
SET @cur_hash = '';
SELECT id,Firstname ,CONCAT(left(Firstname ,3),IF(ndx>=0,CONCAT('00',ndx),'')) Firstname
FROM (SELECT id,
@new_hash := MD5(Firstname ),
(@ndx := IF(@new_hash=@cur_hash,@ndx+1,1)) ndx,
@cur_hash := MD5(Firstname ),
Firstname
FROM (SELECT id,Firstname FROM customer ORDER BY Firstname ) AA) A order by id;
输出:
1 | Anish | Ani001
2 | Uma | Uma001
3 | Anish | Ani002
4 | Uma | Uma002
5 | Loki | Lok001