开发者

Increment string with %name%+(num) in mysql

Is there way to 开发者_开发问答realize this algorithm with mysql without 100500 queries and lots of resources?

if (exists %name% in table.name) {
    num = 2;
    while(exists %newname%+(num) in table.name) num++;
    %name% = newname+(num);
}

Thanks


I don't know how much better you can do with a stored procedure in MySql, but you can definitely do better than 100500 queries:

SELECT name FROM table WHERE name LIKE 'somename%' ORDER BY name DESC LIMIT 1

At that point, you know that you can increment the number at the end of name and the result will be unused.

I 'm glossing over some fine print (this approach will never find and fill any "holes" in the naming scheme that may exist, and it's still not guaranteed that the name will be available due to race conditions), but in practice it can be made to work quite easily.


The simpliest way I can see of doing it is to create a table of sequential numbers then cross join on to it....

SELECT a.name,b.id 
FROM table a
WHERE a.name = 'somename'
CROSS JOIN atableofsequentialnumbers b
WHERE NOT EXISTS (SELECT 1 FROM table x WHERE x.name = CONCAT(a.name,b.id))
LIMIT 10

This will return the first 10 available numbers/names

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜