CREATE TABLE practice_mysql.sample ( id int(11) default NULL, Firstname varchar(45) default NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into sample (id,Firstname) values ('1','Anish');
insert into sample (id,Firstname) values ('2','Anish');
insert into sample (id,Firstname) values ('3','Uma');
insert into sample (id,Firstname) values ('4','Anish');
insert into sample (id,Firstname) values ('5','Uma');
insert into sample (id,Firstname) values ('6','temp');
**
和我尝试这个查询获取名字前3个字母和我有 用于生成自动增量
**
SET @ndx = 0;
SET @cur_hash = '';
SELECT id,Firstname ,CONCAT(left(Firstname ,3),IF(ndx>=0,CONCAT('--00',ndx),'')) BatchNumber
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 sample ORDER BY Firstname ) AA) A order by id;
我尝试了这段代码,但输出错误。这里有什么错误?
Firstname | Batchnumber
---------------------
Anish | Ani001
Anish | Ani001
Uma | Uma001
Anish | Ani001
Uma | Uma001
temp | tem001
但我需要这种类型的输出:
Firstname | Batchnumber
-----------------------
Anish | Ani001
Anish | Ani002
Uma | Uma001
Anish | Ani003
Uma | Uma002
temp | tem001
当多次插入名称时,我增加了批号。但它不起作用。 我会尝试自己找到它,但对我来说很难。任何人都可以解决它吗?