doujing3896 2013-04-25 10:24
浏览 20
已采纳

将零添加到mySQL表行中的特定位置

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?

  • 写回答

2条回答 默认 最新

  • douba3378 2013-04-25 10:32
    关注
    UPDATE yourTable
    SET `link` = REPLACE(`link`, SUBSTRING(`link` from LOCATE('=', `link`) + 1), RIGHT(CONCAT('000000000', SUBSTRING(`link` from LOCATE('=', `link`) + 1)), 9))
    

    See it working live here in an sqlfiddle.

    UPDATE:

    What if I have some links with more url variables? like: index.php?video=123&play=1&search=hello

    That's a bit trickier, but here you go:

    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))
    

    Or you can do it a bit shorter like this:

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

    See sqlfiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测