1

I have a mySQL table with alot of links like this:

id - link
1 | index.php?video=12
2 | index.php?video=345
3 | index.php?video=6789
4 | index.php?video=123&other=variable
5 | www.site.com/index.php?video=456&other=variable

One link per text row. I would like to add zeros before the numbers but it has to be nine numbers in total. so video=12 would be video=000000012 and video=6789 would be video=000006789.

Is there some way to acheive this by using SQL query?

EDIT: the solution tombom submitted worked fine but what if I have links that don't have the video=x variable?

4

2 回答 2

3
UPDATE yourTable
SET `link` = REPLACE(`link`, SUBSTRING(`link` from LOCATE('=', `link`) + 1), RIGHT(CONCAT('000000000', SUBSTRING(`link` from LOCATE('=', `link`) + 1)), 9))

看到它在 sqlfiddle 中现场工作

更新:

如果我有一些包含更多 url 变量的链接怎么办?比如:index.php?video=123&play=1&search=hello

这有点棘手,但你去:

UPDATE yourTable
SET `link` = replace(`link`, substring(`link`, locate('=', `link`) + 1, ABS(locate('&', `link`) - locate('=', `link`) - 1)), right(concat('000000000', substring(`link`, locate('=', `link`) + 1, ABS(locate('&', `link`) - locate('=', `link`) - 1))), 9))

或者你可以像这样短一点:

UPDATE yourTable
SET `link` = , CONCAT(SUBSTRING_INDEX(`link`, '=', 1),'=', LPAD(SUBSTRING(`link` from locate('=', `link`) + 1),9,'0'))

请参阅sqlfiddle

于 2013-04-25T10:32:38.550 回答
0
UPDATE table1 SET `link` = CONCAT(SUBSTRING_INDEX(`link`, '=', 1),'=', LPAD(SUBSTRING_INDEX(`link`, '=', -1),9,'0'))

sqlfiddle

于 2013-04-25T11:23:16.587 回答