2017-01-30 53 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

相关问题