首页 > 解决方案 > Mysql:如何替换字符串的一部分?

问题描述

我想删除以下网址中“x”之后的所有内容:

我有 :

url
/product/dtphdmi230rx?subtype=384
/product/dtphdmi230tx?subtype=385
/product/dtphdmi330rx?subtype=386
/product/dtphdmi330tx?subtype=387

我想要 :

url
/product/dtphdmi230rx
/product/dtphdmi230tx
/product/dtphdmi330rx
/product/dtphdmi330tx

我知道使用 mysql 8.0 很容易,regex_replace但我无法更新我的服务器。mysql 5有什么办法吗?

注意:总是有一个“?” 在 urls 中,它可以是要删除的第一个字符。

感谢帮助

标签: mysqlsqldatabasestring

解决方案


只是:

left(url, locate('x?', url))

DB Fiddle 上的演示

with mytable as (
    select '/product/dtphdmi230rx?subtype=384' url
    union all select '/product/dtphdmi230tx?subtype=385'
    union all select '/product/dtphdmi330rx?subtype=386'
    union all select '/product/dtphdmi330tx?subtype=387'
)
select left(url, locate('x?', url)) from mytable
| 左(网址,定位('x?',网址))|
| :---------------------------- |
| /产品/dtphdmi230rx |
| /产品/dtphdmi230tx |
| /产品/dtphdmi330rx |
| /产品/dtphdmi330tx |

注意:正如 Raymond Nijland 所评论的,如果?字符串中只出现一次并且可以用作要删除的第一个字符,您还可以执行以下操作:

left(url, locate('?', url) - 1)

推荐阅读