如何在mysql中替换子字符串,其中字符串基于其他表列值
我有两个mysql表如何在mysql中替换子字符串,其中字符串基于其他表列值,mysql,Mysql,我有两个mysql表 Component +----+-------------------------+--------+ | OldComponentId | NewComponentId | +----+-------------------------+--------+ | 15 | 85 | | 16 | 86 | | 17 |
Component
+----+-------------------------+--------+
| OldComponentId | NewComponentId |
+----+-------------------------+--------+
| 15 | 85 |
| 16 | 86 |
| 17 | 87 |
+----+-------------------------+--------+
Formulae
+----+-------------------------+--------+
| id | formula_string |
+----+-------------------------+--------+
| 1 | A+15-16+17 |
| 2 | 16+15-17 |
+----+-------------------------+--------+
I want to replace value of formula_string on the basis of NewComponentId as
Formulae
+----+-------------------------+--------+
| id | formula_string |
+----+-------------------------+--------+
| 1 | A+85-86+87 |
| 2 | 86+85-87 |
+----+-------------------------+--------+
我尝试了以下mysql查询,但它不起作用
更新公式fr,组件组件集合公式_字符串=替换(fr.formula_字符串,组件OldComponentId,组件NewComponentId)
请提出解决办法
谢谢。要做到这一点,没有简单的方法。正如您在update语句中所观察到的,替换不会嵌套。他们只是一次换一个 您可以做的一件事是:
update Formulae fr cross join
Component comp
set formula_string = REPLACE(fr.formula_string, comp.OldComponentId, comp.NewComponentId)
where formula_string like concat('%', comp.OldComponentId, '%')
然后继续运行此操作,直到row\u count()
返回0
请注意,您的结构可能会导致无限循环(如果A-->B和B-->A)。你也有一个“混乱”的问题,所以10将被替换为100。这表明您的总体数据结构可能不正确。也许你应该把公式分成几部分。如果它们只是数字和
+
和-
,则可以有一个包含每个组件的值和符号的连接表。那么您的查询就容易多了。公式字符串可以任意长度?是的,它可以任意长度。