2017-01-30 55 views
2

我有一個帶有兩個表的MySQL數據庫。 表1是這樣的:如果列值類似於另一個逗號分隔列,則表中的Mysql將表更新爲另一列

uid | text    |reference | 
------------------------------------- 
1 |     | 1   | 
2 |     | 1,2  | 
3 |     | 2   | 
4 |     | 3   | 
5 |     | 1,3,2,4,5 | 
6 |     | 5   | 
7 |     | 4   | 

表2是這樣的

uid | text    | 
------------------------- 
1 | text1    | 
2 | text2    | 
3 | text3    | 
4 | text4    | 
5 | text5    | 
6 | text6    | 
7 | text7    | 

我想更新表1,使其成爲:

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中的文本列應該更新,比較table1.referencetable2.uid。如果參考值爲1,則對應於table2.uid #1的文本將被複制到table1.text。如果參考值爲1,2,則將複製與table2.uid #1 and #2對應的文本。 謝謝!

回答

0

這個問題說明了爲什麼在一行中存儲逗號分隔值是一種不好的做法。這種關係是有附加關係表更好的建模,你的情況應該是這樣的:

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 

您可以更新在行動中看到此查詢here

相關問題