[英]Increase Alphanumeric VARCHAR Entry by Value 1?
在一個舊的項目中,由於沒有通過設計思考,我有一個實際上應該設置為auto_increment的列,盡管它不能是因為它是字母數字條目,如下所示:
c01
c02
c03
(c99將繼續c100或更多),這封信過去發生過,需要對系統進行大修才能將其取出,因此我更傾向於采用這種方法。
現在我需要一種方法來模擬自己的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);
雖然這個想法是選擇“tag_id”列中的最高條目,然后簡單地將值增加1,但這個不能按原樣運行。
任何想法如何實現這一目標?
順便說一句,我也不確定你是否可以通過這種方式增加一個字母數字輸入,雖然我知道它可以完成,但我不知道如何。
如果要安全地獲取格式為c##..
的標記id的最大整數值,可以使用以下表達式:
max( convert( substring(tag_id, 2) , unsigned integer) )
^^^ largest ^^^^^^^^^ after 'c' ^^^^^^^^^^^^^^^^ convert to positive number
然后你的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');
這將從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.