mysql 选择更新

2021-11-16 00:00:00 append select mysql

明白了:

Table a
ID RelatedBs
1  NULL
2  NULL

Table b
AID ID
1   1
1   2
1   3
2   4
2   5
2   6

需要表 a 具有表 b 中给出的逗号分隔列表.然后表 b 将过时:

Need Table a to have a comma separated list as given in table b. And then table b will become obsolete:

Table a
ID RelatedBs
1  1,2,3
2  4,5,6

这不会遍历所有记录,而只是将一个 'b' 添加到 'table a'

This does not rund through all records, but just ad one 'b' to 'table a'

UPDATE a, b
SET relatedbs = CONCAT(relatedbs,',',b.id)
WHERE a.id = b.aid

更新:谢谢,3 个正确答案(标记为最旧的答案)!GROUP_CONCAT 是要使用的.无需使用由 GROUP_CONCAT 自动完成的 relatedids = CONCAT(relatedids,',',next_id) 在 id 之间插入逗号.

UPDATE: Thanks, 3 correct answers (marked oldest as answer)! GROUP_CONCAT is the one to use. No need to insert commas between the ids using relatedids = CONCAT(relatedids,',',next_id) that is done automatic by GROUP_CONCAT.

推荐答案

您必须使用 mysql group_concat 函数才能实现此目的:http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat

You'll have to use the mysql group_concat function in order to achieve this: http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat

相关文章