[英]Mysql update column from a table to another one if column value is similar to another comma separated column
我有一個帶有兩個表的MySQL數據庫。 Table1看起來像這樣:
uid | text |reference |
-------------------------------------
1 | | 1 |
2 | | 1,2 |
3 | | 2 |
4 | | 3 |
5 | | 1,3,2,4,5 |
6 | | 5 |
7 | | 4 |
Table2看起來像這樣
uid | text |
-------------------------
1 | text1 |
2 | text2 |
3 | text3 |
4 | text4 |
5 | text5 |
6 | text6 |
7 | text7 |
我想更新Table1使其變為:
uid | text | reference |
---------------------------------------------------
1 | text1 | 1 |
2 | text2 text2 | 1,2 |
3 | text2 | 2 |
4 | text3 | 3 |
5 | text1 text3 text2 text2 text5 | 1,3,2,4,5 |
6 | text5 | 5 |
7 | text4 | 4 |
我發現以下命令,但無法使其適應我的情況
UPDATE table1 AS text
INNER JOIN table2 AS text
ON table1.reference = table2.reference
SET table1.text = table2.text
應該將table1.reference
與table2.uid
相比較,更新table1
的text列。 如果參考值為1,則對應於table2.uid #1
的文本將被復制到table1.text
。 如果reference為1,2,則將復制table2.uid #1 and #2
對應的文本。 謝謝!
此問題說明了為什么在單行中存儲逗號分隔的值是一種不好的做法。 可以使用附加的關系表更好地對這種關系進行建模,在您的情況下,看起來像這樣:
TableRef
uid |referenceUid |
--------------------
1 | 1 |
2 | 1 |
2 | 2 |
3 | 2 |
4 | 3 |
5 | 1 |
5 | 2 |
5 | 3 |
5 | 4 |
5 | 5 |
... | ... |
這樣,您可以像這樣進行所需的更新
update Table1 t1, (
select t3.uid, group_concat(t2.text order by t2.text separator ' ') as text
from TableRef t3
join Table2 t2
on t3.referenceUid = t2.uid
group by t3.uid
) t4
set t1.text = t4.text
where t1.uid = t4.uid
您可以在此處查看此查詢的運行情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.