使用 group concat 插入 Select

Insert into Select with group concat

你好,我有一个 table 值

 domain                 user              groups
 test_at_test.com         john              first
 test_at_test.com         mary              second
 test_at_test.com         john              second

等..

我想 group concat table 并将值插入新的 table 或 update 当前 table 我没有问题并让新的 table 变成这样

domain                user              groups
test_at_test.com         john              first,second
test_at_test.com         mary              second

我写了以下 command 但我得到 error 列数与第 1 行的值数不匹配 INSERT INTO newtable SELECT * , GROUP_CONCAT(groups) FROM table GROUP BY user ORDER BY domain

您的新 table 有 3 列,但在 select 中,结果集将有 4 列,您需要在 select 语句

中指定列
INSERT   INTO    newtable 
SELECT `domain`, `user`,  GROUP_CONCAT(groups)  
FROM table GROUP BY  user 
ORDER BY domain

DEMO

Note The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet.