[英]Increase Alphanumeric VARCHAR Entry by Value 1?
On an old project because of not thought through design I have a column which actually should be set to auto_increment, though it cannot be because it are alphanumeric entries as follows: 在一个旧的项目中,由于没有通过设计思考,我有一个实际上应该设置为auto_increment的列,尽管它不能是因为它是字母数字条目,如下所示:
c01
c02
c03
(c99 would continue to c100 and more), the letter happened in the past and it would require to overhaul the system to take it out, thus I rather prefer this workaround. (c99将继续c100或更多),这封信过去发生过,需要对系统进行大修才能将其取出,因此我更倾向于采用这种方法。
Now I need a way to imitate the auto_increment
functionality with the SQL statement myself, my own attempt has gotten as far as the following: 现在我需要一种方法来模拟自己的SQL语句的
auto_increment
功能,我自己的尝试已经达到以下目的:
INSERT INTO tags (tag_id, tag_name, tag_description, added_by_user_id, creation_date, last_edited) VALUES (SELECT(MAX(tag_id)+1),
'Love', 'All about love', 7, now(), 0);
This one does not work as is, though the idea was to select the highest entry in the column "tag_id" and then simply increase it by the value 1. 虽然这个想法是选择“tag_id”列中的最高条目,然后简单地将值增加1,但这个不能按原样运行。
Any ideas how to accomplish this? 任何想法如何实现这一目标?
By the way I am also not sure if you simply can increase an alphanumeric entry through this way, though I know it can be done, I just don't know how. 顺便说一句,我也不确定你是否可以通过这种方式增加一个字母数字输入,虽然我知道它可以完成,但我不知道如何。
If you want to safely get the largest integer value of a tag id of the form c##..
, you could use the following expression: 如果要安全地获取格式为
c##..
的标记id的最大整数值,可以使用以下表达式:
max( convert( substring(tag_id, 2) , unsigned integer) )
^^^ largest ^^^^^^^^^ after 'c' ^^^^^^^^^^^^^^^^ convert to positive number
Then your insert statement would look something like this: 然后你的insert语句看起来像这样:
set @newid = convert(
(select
max(convert( (substring(tag_id, 2)) , unsigned integer))+1
from tags), char(10)
);
set @newid = if(length(@newid) = 1, concat('0', @newid), @newid);
set @newid = concat('c', @newid);
INSERT INTO tags (tag_id, tag_name, tag_description, added_by_user_id,
creation_date, last_edited)
VALUES (@newid, 'Love', 'All about love', 7, now(), '2012-04-15');
Demo: http://www.sqlfiddle.com/#!2/0bd9f/1 演示: http ://www.sqlfiddle.com/#!2/ 0bd9f/1
this will increase from c01 to c02 to c03 ... to c99 to c100 to c101 ... to c999 to c1000 etc. 这将从c01增加到c02到c03 ...到c99到c100到c101 ...到c999到c1000等。
set @nextID = (SELECT CONCAT(SUBSTRING(`tag_id`, 1, 1), IF(CHAR_LENGTH(CAST(SUBSTRING(`tag_id`, 2)
AS UNSIGNED)) < 2, LPAD(CAST(CAST(SUBSTRING(`tag_id`, 2) AS UNSIGNED) + 1 AS CHAR), 2,
'0'), CAST(CAST(SUBSTRING(`tag_id`, 2) AS UNSIGNED) + 1 AS CHAR))) FROM `tags` ORDER BY
`tag_id` DESC LIMIT 1);
INSERT INTO tags (tag_id, tag_name, tag_description, added_by_user_id,
creation_date, last_edited) VALUES (@nextID, 'Love', 'All about love', 7, NOW(), null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.