美文网首页
mysql GROUP_CONCAT 分组拼接合并后,更新到关联

mysql GROUP_CONCAT 分组拼接合并后,更新到关联

作者: 一介书生独醉江湖 | 来源:发表于2023-05-25 20:07 被阅读0次
# 表1 nsp_dossier  、表2 nsp_dossier_matter (多); 
# 两表之间是一对多的关系;

# nsp_dossier 表
dossier_id (唯一)    testimony  modify_dt  apply_time
 d1                     null       null    2017-01-22
 d2                     null       null    2017-01-22

# nsp_dossier_matter 表
dossier_matter_id(唯一)dossier_id     testimony  apply_time
m1                         d1           t1_txt    2017-01-22
m2                         d2           t2_txt    2017-01-22
m3                         d1           t3_txt    2017-01-22
m4                         d2           t4_txt    2017-01-22

# 期望结果 nsp_dossier 表
dossier_id (唯一)  testimony             modify_dt           apply_time
 d1                t1_txt,t3_txt       2023-05-26 19:57:39    2017-01-22
 d2                t2_txt,t4_txt       2023-05-26 19:57:39    2017-01-22
# 现在想将nsp_dossier_matter 表中的 testimony 拼接合并后,再更新到对应的nsp_dossier表中testimony字段;

set sql_safe_updates = 0;

  UPDATE nsp_dossier n
    INNER JOIN (
        SELECT dossier_id, GROUP_CONCAT(testimony SEPARATOR ',') as testimony
        FROM nsp_dossier_matter
        WHERE apply_time <= '2017-06-22' and apply_time >= '2017-01-22'
        GROUP BY dossier_id
    ) m
    ON n.dossier_id = m.dossier_id
SET n.testimony = m.testimony, n.modify_dt = NOW()
WHERE n.dossier_id = m.dossier_id
    AND n.apply_time <= '2017-06-22' and n.apply_time >= '2017-01-22';
# 注意 如果group_concat_max_len长度太小,但实际拼接字段太长会出错,增加长度即可;

# 查看当前 mysql group_concat_max_len ,默认1024;
show variables like 'group_concat_max_len';

#全局
SET GLOBAL group_concat_max_len=102400;

#会话级
SET SESSION group_concat_max_len = 10240000;

# 设置最大
SET GLOBAL / SESSION group_concat_max_len = -1;



相关文章

网友评论

      本文标题:mysql GROUP_CONCAT 分组拼接合并后,更新到关联

      本文链接:https://www.haomeiwen.com/subject/bsihedtx.html