我在 MySQL 表中有数千个字符串
some-text-for-read/id123456
some-other-text-to-read-too/id456789
我想做他们
/id123456
/id456789
如何在文本部分使用通配符? 我尝试了我发现的一切 “替换 %id%” 类似的查询,但没有任何效果,因为我可能没有做对。
最佳答案
结合使用 MySQL string functions LOCATE()
和 SUBSTR()
,您可以使用 LOCATE()
查找字符串中的位置第一个 /
字符,SUBSTR()
返回子字符串以在原始字符串中的那个位置开始。
您可以将所有这些放入 UPDATE
语句中:
UPDATE your_table
SET your_column = SUBSTR(your_column, LOCATE('/', your_column))
-- Only on rows where the / is present, if there are non-matching rows
-- LOCATE() returns 0 when the string isn't found
WHERE LOCATE('/', your_column) > 0
例子:
> SELECT SUBSTR('some-other-text-to-read-too/id456789', LOCATE('/', 'some-other-text-to-read-too/id456789')) AS val;
+-----------+
| val |
+-----------+
| /id456789 |
+-----------+
以及您需要 WHERE
子句的原因——如果行中没有 /
,所有内容都将被删除:
/* This has no '/' */
> SELECT SUBSTR('some-other-text-to-read-tooid456789', LOCATE('/', 'some-other-text-to-read-tooid456789')) AS val;
+-----+
| val |
+-----+
| |
+-----+
关于mysql - 如何使用通配符删除/替换mysql中的部分字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28205608/