簡體   English   中英

MySQL替換-操縱字符串的一部分

[英]MySQL replace - manipulate portion of string

在mysql表中有一個包含相對URL和其他URL的列,我想將最后一位跳10000(對於相對URL)

...
index.php?option=com_content&view=article&id=220
index.php?option=com_content&view=article&id=221
index.php?option=com_content&view=article&id=222
http://somerandomurl.com
index.php?option=com_content&view=article&id=227
http://anotherrandomurl.com
...

我知道如何替換字符串的固定部分,但我仍然不知道如何以編程方式更改字符串的一部分,從而導致這種模式

...
index.php?option=com_content&view=article&id=10220
index.php?option=com_content&view=article&id=10221
index.php?option=com_content&view=article&id=10222
http://somerandomurl.com
index.php?option=com_content&view=article&id=10227
http://anotherrandomurl.com
...


UPDATE url_table
SET url_field = REPLACE ?????????
WHERE url_field LIKE '%index.php?option=com_content&view=article&id=%'

是否有一種簡單的方法來實現此操作?

如果數字始終為3位數字,則可以使用以下代碼:

UPDATE url_table
SET url_field = replace(url_field,right(url_field,3),right(url_field,3)+10000)
WHERE url_field = LIKE '%index.php?option=com_content&view=article&id=%'

我不確定mysql如何處理字符串類型列中的數字,所以如果它不接受它:

UPDATE url_table
SET url_field = replace(url_field,right(url_field,3),
                       cast(right(url_field,3) to number) +10000 to string)
WHERE url_field = LIKE '%index.php?option=com_content&view=article&id=%'

如果總是需要從右邊插入3位數字,則@sagi的答案是正確的。 但是,如果不是這種情況,則需要正則表達式。 自版本10起的MariaDB具有REGEXP_REPLACE函數,可使用正則表達式替換字符串。 如果您不使用MariaDB, 此討論可能會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM