![](/img/trans.png)
[英]MySQL complex SQL query showing empty values where a table-column doesn't match
[英]How to replace substring in mysql where string is based on other table-column values
我有兩個mysql表作為
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,組件補償集Formula_string = REPLACE(fr.formula_string,comp.OldComponentId,comp.NewComponentId)。
請提出解決方案
謝謝。
沒有簡單的方法可以做到這一點。 正如您在更新語句中觀察到的那樣,替換項不會嵌套。 他們只是一次替換一個。
您可以做的一件事是:
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_count()
返回0
。
請注意,您的結構可能會導致無限循環(如果A-> B和B-> A)。 您還存在“混亂”的問題,因此10可以替換為100。這表明您的整體數據結構可能不正確。 也許您應該將公式分解為幾個部分。 如果它們只是數字以及+
和-
,則可以有一個連接表,其中包含每個組件的值和符號。 這樣您的查詢會容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.