我正在尝试更新具有多行串联值的字段。
所以有表a:
ID | single_value
1 | hello
2 | something
1 | world
42 | another someting
1 | bye bye
...
和表b:
ID | concated_field
1 | '' (i.e. empty )
2 | ''
3 | ''
4 | ''
结果,表 b 应该是:
ID | concated_field
1 | hello, world, bye bye
2 | something
3 | ''
42 | another something
...
我的查询是:
update data.table b, data.content a
set b.concated_field= (
select group_concat(single_value separator ', ') from data.table
)
where b.ID= a.ID;
但我的结果是这样的:
ID | concated_field
1 | hello, something, world,another something, bye bye
2 | ''
3 | ''
42 | ''
...
似乎 WHERE 部分是错误的,但我不明白。 我正在认真寻求帮助! :)
最佳答案
您需要在子查询中使用 WHERE
和 GROUP BY
子句才能达到预期结果。
update data.table b, data.content a
set b.concated_field= (
select group_concat(single_value separator ', ')
from data.table
where data.table.ID = b.ID
group by data.table.ID
)
where b.ID= a.ID;
关于mysql group_concat 作为 set 语句的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594002/